我有一个简单的程序,使用StreamReader读取文件并逐行处理。但是我正在读取的文件有时可能位于网络文件夹中。在对这样的文件进行一些测试时,我遇到了一个问题:如果在读取过程中某个时刻丢失了网络连接,那么StreamReader将一直停留在同一行,并通过从流中读取相同的行来循环无限次。
有没有办法从流本身找出fileHandle不可用的情况?当StreamReader丢失文件句柄时,我希望会触发类似FileNotAvailableException的异常。
这是我的代码片段...
string file = @"Z://1601120903.csv"; //Network file
string line;
StringBuilder stb = new StringBuilder();
StreamReader stream = new StreamReader(file, Encoding.UTF8, true, 1048576);
do
{
line = stream.ReadLine();
// Do some work here
} while (line != "");