Yoshi Walsh
Yoshi Walsh

Reputation: 2077

System.IO.DirectoryNotFoundException by File.Move

Just a quick question (I hope): When I use File.Move it gives me an error:

System.IO.DirectoryNotFoundException was unhandled by user code
  Message=Could not find a part of the path.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.__Error.WinIOError()
       at System.IO.File.Move(String sourceFileName, String destFileName)
       at Portal_2_Level_Installer.Form1.WorkMagic(String FileLocation) in C:\Users\Yoshie\Local Settings\Documents\Visual Studio 2010\Projects\Portal 2 Level Installer\Portal 2 Level Installer\Form1.cs:line 265
  InnerException: 

My code:

File.Move(FileLocation, destinationPath);

And the contents of the variables:

destinationPath="c:/program files (x86)/steam\\steamapps\\common\\portal 2\\Test\\Test.docx"
FileLocation="C:\\Users\\Yoshie\\Local Settings\\Documents\\Test.docx"

Thanks! EDIT: I really feel like an idiot now. I didn't realise that the destination folder had to exist! I stupidly assumed that the destination folder would be automatically created if it didn't already exist. Sorry for wasting your time, but thanks for the answers anyway! (I now know that I can use @ to stop escaping, so thats good to know) Thanks anyway, and again, sorry!

Upvotes: 8

Views: 5834

Answers (5)

Wappenull
Wappenull

Reputation: 1409

In my case (WinForm .NET Framework 4.7.2), using the File.Move with a path longer than MAX_PATH (around 260 characters) seems to also trigger this exception.

So I prepend the path I used with long path syntax before passing to File.Move and it worked.

// Prepend long file path support
if( !packageFile.StartsWith( @"\\?\" ) )
    packageFile = @"\\?\" + packageFile;

See: How to deal with files with a name longer than 259 characters?

Upvotes: 0

WhoIsRich
WhoIsRich

Reputation: 4153

I was also caught out by this TargetInvocationException when doing File.Delete and did not notice the inner message of make sure the directory exists.

This was due to me switching from Release to Debug and I had failed to create a set of relative subfolders that would of contained the file to be deleted.

Upvotes: 0

Rasel
Rasel

Reputation: 15477

Your destination file path should be like this

destinationPath="c:\\program files (x86)\\steam\\steamapps\\common\\portal 2\\Test\\Test.docx"

Upvotes: 0

Zenwalker
Zenwalker

Reputation: 1919

Please use \ and not / as well as use @ like @"path".

Upvotes: 3

Haris Hasan
Haris Hasan

Reputation: 30127

Does this make any difference?

destinationPath=@"c:\program files (x86)\steam\steamapps\common\portal 2\Test\Test.docx";
FileLocation=@"C:\Users\Yoshie\Local Settings\Documents\Test.docx";

Upvotes: 2

Related Questions