Posts Tagged ‘Could not find a part of the path’

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}