【问题标题】:System.IO.DirectoryNotFoundException by File.MoveFile.Move 的 System.IO.DirectoryNotFoundException
【发布时间】:2011-10-25 16:39:43
【问题描述】:

只是一个简单的问题(我希望): 当我使用 File.Move 时,它​​给了我一个错误:

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: 

我的代码:

File.Move(FileLocation, destinationPath);

以及变量的内容:

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

谢谢! 编辑:我现在真的觉得自己像个白痴。我没有意识到目标文件夹必须存在!我愚蠢地假设如果目标文件夹不存在,它会自动创建。很抱歉浪费您的时间,但还是感谢您的回答! (我现在知道我可以使用 @ 来停止转义,所以很高兴知道) 无论如何,谢谢,再次抱歉!

【问题讨论】:

  • 你检查了 destinationPath 吗?它有正斜杠和反斜杠!重新检查!
  • c:/program files (x86)/ 应该是 c:\\program files (x86)\\
  • @Anton,不,他们不是。至少以 c# 方式。
  • +1 提供一个清晰的例子并承认你的错误。如果更多的程序员能够承认自己的错误,我们的行业就会变得更好:)

标签: c# file-io


【解决方案1】:

这有什么不同吗?

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

【讨论】:

  • -1:也因为不知道 / 和 \ 是一回事,而且都是有效的。
【解决方案2】:

请使用 \ 而不是 / 以及像 @"path" 一样使用 @。

【讨论】:

  • 我是把@放在原路径前​​面还是目的地前面?
  • 我可以做 File.Move(@FileLocation, @destinationPath);代替?
  • -1: / 与 `\` 一样有效。无需决定个人喜好:)
  • 有趣的是,我主要关心编译器是否理解我的代码。我实际上发现/ 更具可读性,但正如我所说,这只是个人意见。
【解决方案3】:

你的目标文件路径应该是这样的

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

【讨论】:

    【解决方案4】:

    我在执行 File.Delete 时也被此 TargetInvocationException 捕获,并没有注意到确保目录存在的内部消息。

    这是由于我从 Release 切换到 Debug 并且我未能创建一组包含要删除的文件的相关子文件夹。

    【讨论】:

      【解决方案5】:

      在我的情况下(WinForm .NET Framework 4.7.2),使用路径长于 MAX_PATH(大约 260 个字符)的 File.Move 似乎也会触发此异常。

      因此,我在传递给File.Move 之前使用长路径语法预先添加了我使用的路径,并且它起作用了。

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

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

      【讨论】:

        猜你喜欢
        • 2016-05-17
        • 1970-01-01
        • 2011-02-13
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 1970-01-01
        • 2018-12-01
        • 2014-06-25
        相关资源
        最近更新 更多