【问题标题】:File.Copy mysteryFile.Copy之谜
【发布时间】:2018-03-13 17:59:36
【问题描述】:

我有如下代码(其实是分了各种方法,不过是这样的):

string ThePath = FBD.SelectedPath; // FBD is a FolderBrowserDialog.
string TheSubDirPath = Path.Combine(ThePath, TheSubDirName);
if (Directory.Exists(TheSubDirPath)) {      Directory.Delete(TheSubDirPath, true); } // Want a clean, empty directory.
Directory.CreateDirectory(TheSubDirPath);
string TheSrcFileName = Path.Combine(ThePath, MyOldFileName);
string TheDestFileName = Path.Combine(TheSubDirPath, MyNewFileName);
File.Copy(TheSrcFileName, TheDestFileName, false); // Overwriting is impossible, so not needed.

最后一行导致带有消息的 DirectoryNotFoundException

找不到路径“C:\Users...\Test01\TheSubDirName\MyNewFileName”的一部分。”

源路径和目标路径都正是我想要的。 我尝试在目录删除后和目录创建后插入延迟,但没有效果。我有一个堆栈跟踪,它显示了问题的核心

在 System.IO.Error.WinIOError(Int32 errorCode, String maybeFullPath)

在 System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)

在 System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)

有什么想法吗?

【问题讨论】:

  • TheSrcFileNameTheDestFileName 的值是多少?
  • 您的代码对我来说可以正常工作,即使c:\users...\dunsany 中有三个点也是如此。请分享足够的信息,以便我们重现该问题。
  • 如果TheSubDirPath 已经作为目录以外的东西存在怎么办?
  • TheSrcFileName 是 "C:\Users\MyName\Documents\Test01\filename.ext"
  • TheDestFileName 是 C:\Users\MyName\Documents\Test01\subdirname\anotherfilename.ext"

标签: c# file-io


【解决方案1】:

将 if 条件替换为:

if (Directory.Exists(TheSubDirPath))
    Directory.Delete(TheSubDirPath, true);

【讨论】:

    【解决方案2】:

    可能会出现以下情况 调用 Directory.Delete(TheSubDirPath, true) 方法的结果可能会将文件夹保留为“待删除”。因此,您可能在创建新文件夹后删除了文件夹。换个说法试试

    if (Directory.Exists(TheSubDirPath))
            Directory.Delete(TheSubDirPath, true);
    

    while(Directory.Exists(TheSubDirPath))
    {
        Directory.Delete(TheSubDirPath, true);
        Sleep(); //Somehow like Thread.Sleep()
    }
    

    【讨论】:

    • 这似乎已经解决了!非常感谢你们!'while (Directory.Exists(TheSubPath)){Directory.Delete(TheSubPath.true);Thread.Sleep(1000);}
    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    相关资源
    最近更新 更多