FileSystemWatcher - 无法读取创建的文件
FileSystemWatcher - unable to read created file
我最近开始使用 FileSystemWatcher
。我需要监视某个目录,并且添加到该目录的任何新文件都会获取 MD5 校验和并将其显示在控制台中。所以我添加了适当的事件处理程序
watcher.Created += new FileSystemEventHandler(OnCreated);
然后 OnCreated
看起来像
private static void OnCreated(object sender, FileSystemEventArgs e)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead("C:\Test\Uploads\"+ e.Name))
{
byte[] checkSum = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < checkSum.Length; i++)
{
sb.Append(checkSum[i].ToString());
}
Console.WriteLine(sb.ToString());
}
}
}
创建第一个文件时,这工作得很好,但是一旦在目录中创建另一个文件,我就会收到以下错误
Additional information: The process cannot access the file 'C:\Test\Uploads\New Text Document (2).txt' because it is being used by another process
引发错误的行是
using (var stream = File.OpenRead("C:\Test\Uploads\"+ e.Name))
我也试过 stream.Dispose();
但遇到了同样的问题。有谁知道我哪里出错了?预先感谢您的所有帮助和支持。
如上所述,重试这个简单的超时
using (var md5 = MD5.Create())
{
int retries = 10;
while (retries > 0)
{
try
{
using (var stream = File.OpenRead("C:\Test\Uploads\" + e.Name))
{
byte[] checkSum = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < checkSum.Length; i++)
{
sb.Append(checkSum[i].ToString());
}
}
// All done, leave the loop
break;
}
catch (FileNotFoundException e)
{
// Check for your specific exception here
retries--;
Thread.Sleep(1000);
}
}
// Do some error handling if retries is 0 here
}
请注意,在 Catch 块中,您必须正确检查您的特定错误。在任何其他情况下,您想处理异常。
我最近开始使用 FileSystemWatcher
。我需要监视某个目录,并且添加到该目录的任何新文件都会获取 MD5 校验和并将其显示在控制台中。所以我添加了适当的事件处理程序
watcher.Created += new FileSystemEventHandler(OnCreated);
然后 OnCreated
看起来像
private static void OnCreated(object sender, FileSystemEventArgs e)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead("C:\Test\Uploads\"+ e.Name))
{
byte[] checkSum = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < checkSum.Length; i++)
{
sb.Append(checkSum[i].ToString());
}
Console.WriteLine(sb.ToString());
}
}
}
创建第一个文件时,这工作得很好,但是一旦在目录中创建另一个文件,我就会收到以下错误
Additional information: The process cannot access the file 'C:\Test\Uploads\New Text Document (2).txt' because it is being used by another process
引发错误的行是
using (var stream = File.OpenRead("C:\Test\Uploads\"+ e.Name))
我也试过 stream.Dispose();
但遇到了同样的问题。有谁知道我哪里出错了?预先感谢您的所有帮助和支持。
如上所述,重试这个简单的超时
using (var md5 = MD5.Create())
{
int retries = 10;
while (retries > 0)
{
try
{
using (var stream = File.OpenRead("C:\Test\Uploads\" + e.Name))
{
byte[] checkSum = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < checkSum.Length; i++)
{
sb.Append(checkSum[i].ToString());
}
}
// All done, leave the loop
break;
}
catch (FileNotFoundException e)
{
// Check for your specific exception here
retries--;
Thread.Sleep(1000);
}
}
// Do some error handling if retries is 0 here
}
请注意,在 Catch 块中,您必须正确检查您的特定错误。在任何其他情况下,您想处理异常。