【发布时间】:2014-08-21 19:53:03
【问题描述】:
当我将同一个文件 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)
当我调试该部分时,不会抛出异常。
【问题讨论】:
-
我无法复制此文件 - 我可以多次粘贴文件并且不会引发异常。你每次都得到例外吗?你在哪个平台上运行?
-
是的,我每次都遇到异常。我正在运行 Windows 8.1 专业版。当我关闭我的程序并重新启动它时,我会在将相同的文件复制到文件夹 A 后立即得到异常。
标签: c#