评论结果:
应用程序崩溃是由另一个问题引起的
我从2个不同的应用程序读取/写入文件,当文件正在被读取或写入时,它将始终被应用程序A或B锁定,并且它们都使用FileShare.None
。
我的问题是,即使将阅读器封装在try/catch中,它仍会在using行处崩溃应用程序并出现IOException(写入程序不会发生这种情况)。
我还将catch设置为catch (IOException ...
,我相信除了使其更易读之外,没有任何区别。
忽略文件被锁定的正确方法是什么,如何保持尝试直到文件可用?
while (true)
{
try
{
using (FileStream stream = new FileStream("test_file.dat", FileMode.Open, FileAccess.Read, FileShare.None))
{
using (TextReader reader = new StreamReader(stream))
{
// bla bla bla does not matter
}
}
}
catch
{
// bla bla bla does not matter again
}
Thread.Sleep(500);
}
编写
private bool WriteData(string data)
{
try
{
using (FileStream stream = new FileStream("test_file.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
stream.SetLength(0);
using (TextWriter writer = new StreamWriter(stream))
{
writer.Write(data);
}
}
return true;
}
catch
{
return false;
}
}
请注意,无论是读取还是写入文件,当文件用于任何过程时,我都不会授予任何人共享权限(包括作者和读者使用
FileShare.None
)。因此,基本上我一直在处理异常,直到文件可用为止,但这并没有起作用。
catch
语句块中使用了throw
(不确定你是没有把代码放在catch
中还是确实为空),要么该文件被多个位置访问,因此这不是实际引发异常的代码。现有的catch
一定可以捕获IOException
。 - Joachim Isaksson