繁体   English   中英

File.Copy之谜

[英]File.Copy mystery

我有以下代码(实际上是在各种方法之间划分的,但这就是它的意思):

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,可能是StringFullPath)

在System.IO.File.InternalCopy(String sourceFileName,String destFileName,布尔覆盖,布尔checkHost)

在System.IO.File.Copy处(字符串sourceFileName,字符串destFileName,布尔覆盖)

有任何想法吗?

当调用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()
}

如果条件替换为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM