gpt4 book ai didi

c# - 移动文件 3 次时出现异常

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:42 25 4
gpt4 key购买 nike

当我将同一个文件复制 3 次到文件夹 A 时,为什么会出现 IOException(进程无法访问该文件,因为它正在被另一个进程使用。)

class FileWatcher {

FileSystemWatcher fsw;
FileInfo file;
string destination = @"C:\FileMover\B\";
Random random;

public FileWatcher() {
fsw = new FileSystemWatcher();
random = new Random();

fsw.Path = @"C:\FileMover\A";

fsw.Created += fsw_Created;

fsw.EnableRaisingEvents = true;
}

void fsw_Created(object sender, FileSystemEventArgs e) {
string destinationFileName = destination + e.Name;

if (!File.Exists(destinationFileName)) {
file = new FileInfo(e.FullPath);
file.MoveTo(destinationFileName);
}
else {
file = new FileInfo(e.FullPath);
file.MoveTo(destinationFileName + random.Next());
}
file = null;
}
}

主要内容:

class Program {      
static void Main(string[] args) {

FileWatcher watcher = new FileWatcher();

while (Console.ReadKey().Key != ConsoleKey.Q) {

}
}
}

2 次后文件夹 B 包含 2 个文件(sourceFileName 和 sourceFileName1274968236)

当我调试该部分时,不会抛出任何异常。

最佳答案

Created 可能会在文件刷新(?)到目标位置之前引发。尝试使用 Changed 并检查 e.ChangeType==WatcherChangeTypes.Created

引用:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created(v=vs.110).aspx

编辑:Changed 事件在 Created 之后引发,如果这是由于竞争条件引起的,可能会有所帮助,但问题仍可能发生。

The OnCreated event is raised as soon as a file is created. If a file is being copied or transferred into a watched directory, the OnCreated event will be raised immediately, followed by one or more OnChanged events.

找到这个:Wait Until File Is Completely Written还有这个:Is there a way to check if a file is in use?

关于c# - 移动文件 3 次时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25434801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com