Could not find a part of the path

Posted: January 5, 2011 in File Operations
Tags: , , ,

I came across this error “Could not find a part of the path” while copying a file from one location to another.It threw exception at the second parameter of this below line

File.Copy(Path,FilePath + @"\" +FileName, true);

Value expected for this second parameter was like this C:\Templates\ANUTESTCODE11\test.xml where the test.xml gets added from the value of FileName.At one particulat section of calling code,the FileName was null & It was reading as C:\Templates\ANUTESTCODE11\ which resulted in the error message “Could not find a part of the path”

I found this during unit testing & this scenario has to be handled in the code.You should not give a chance for your code to fail & the appropriate way of using File.Copy is as below.This code snippet was suggested by one of the readers & adding it here.

{ if (!string.IsNullOrEmpty(FileName))
{ string newPath = System.IO.Path.Combine(FilePath, FileName);
if (File.Exists(Path) && Path.ToLower() != newPath.ToLower())
File.Copy(Path, newPath, true);

catch (Exception ex){ // handle the exception as desired}
  1. Sumit Thomas says:

    It would be better if throw a ArgumentNullException with custom message if any of the required parameter is null.

  2. Anupama says:

    Thank you Sumit!That’s a great suggestion .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s