开发者

System.IO.DirectoryNotFoundException by File.Move

开发者 https://www.devze.com 2023-03-27 21:02 出处:网络
Just a quick question (I hope): When I use File.Move it gives me an error: System.IO.DirectoryNotFoundException was unhandled by user code

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!


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


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";


Your destination file path should be like this

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


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消