0

My File.Copy(xxx,xxx, true) is throwing an unhandled exception I understand that File.copy does not allow me to use a directory but in my case my filename can change every time I go through the loop. I need the filename to be the same as it appears in my source folder. Here is what I have so far. Any Ideas? I looked at MSDN but it defines my problem, not a solution. Any help appreciated.

//Get Data from Filename string[] files = System.IO.Directory.GetFiles(sourcePath, "Result*.xml"); Regex date = new Regex(@"(?<month>[1-9]|[0-2])_(?<day>\d{2})_(?<year>\d{4})", RegexOptions.CultureInvariant); foreach (string s in files) { Match m = date.Match(s); if (m.Success) { //Pass Groups to String string month = m.Groups["month"].Value; string day = m.Groups["day"].Value; string year = m.Groups["year"].Value; //Create Dir var paths = new string[] { targetPath, year, month, day }; string result = paths.Aggregate(Path.Combine); Directory.CreateDirectory(result); //Copy file File.Copy(s, result, true); } } 
4
  • 6
    Shall I look into my crystal ball and guess what your exception is, or would you like to tell us instead? There's 8 different possible exceptions that can be thrown by File.Copy Commented Sep 16, 2013 at 16:54
  • 1
    I think you're confused when you say File.Copy doesn't allow you to use a directory - it absolutely does. You're supposed to pass the full path of the files in question, not just the names. See my answer below. Commented Sep 16, 2013 at 17:07
  • 1
    Also, please learn to read documentation. If you had, you'd notice that result "...cannot be a directory" which is what you're passing it. Additionally it has examples that show using a path (I don't know where you got that it doesn't allow a path). Commented Sep 16, 2013 at 17:16
  • Thank you tnw. my exception was "The target file "C:\Users\wike01\Desktop\sorted\2009\5\14" is a directory, not a file." in case your crystal ball was malfunctioning. I made a mistake by not proofing my post well enough. I typed path but I should have said directory. I have this corrected now thanks to Magnus but your sarcasm was extremely helpful.......... Commented Sep 16, 2013 at 18:21

1 Answer 1

2

I think your mistake is that you aren't including the filename in the destination parameter.

string filename = Path.GetFileName(s); string newPath = Path.Combine(result, filename); File.Copy(s, newPath, true); 
Sign up to request clarification or add additional context in comments.

1 Comment

That nails it on the head sir. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.