简体   繁体   English

File.Copy之谜

[英]File.Copy mystery

I have the following code (actually divided among various methods, but this is what it amounts to): 我有以下代码(实际上是在各种方法之间划分的,但这就是它的意思):

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.

This last line is causing a DirectoryNotFoundException with the message 这最后一行导致DirectoryNotFoundException与消息

Could not find a part of the path 'C:\\Users...\\Test01\\TheSubDirName\\MyNewFileName'." 找不到路径'C:\\ Users ... \\ Test01 \\ TheSubDirName \\ MyNewFileName'的一部分。”

Both the source and destination paths are exactly what I want them to be. 源路径和目标路径都正是我想要的。 I have tried inserting delays after the directory deletion and after the directory creation, to no effect. 我尝试在目录删除后和目录创建后插入延迟,但没有任何效果。 I have a stack trace which shows the heart of the problem 我有一个堆栈跟踪显示了问题的根源

at System.IO.Error.WinIOError(Int32 errorCode, String maybeFullPath) 在System.IO.Error.WinIOError(Int32 errorCode,可能是StringFullPath)

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

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

Any ideas? 有任何想法吗?

Potentially there might be a situation when a result of calling the method Directory.Delete(TheSubDirPath, true) might leave the folder as 'to be removed'. 当调用Directory.Delete(TheSubDirPath, true)方法的结果可能会使文件夹保留为“待删除”状态。 So potentially, you might have removed folder after creating a new one. 因此,潜在地,您可能在创建新文件夹后删除了该文件夹。 Try to change the statement 尝试更改语句

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

with

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

replace if condition with : 如果条件替换为:

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

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

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