我在这里的原始相关问题(https://stackoverflow.com/questions/17332403/is-there-such-ac-sharp-method-or-methodology-that-would-equate-to-filealready)被标记为重复,并且我使用了假定的重复项(Is there a way to check if a file is in use?)来尝试解决我的问题,但在某些文件 I/O 操作上仍然出现空引用异常。
基于昔日的 halcyon 帖子,我将之前的代码改成了:
public FileQuickRead(string filename)
{
try
{
SR = File.OpenText(filename);
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileQuickRead");
}
. . .
...对此:
public FileQuickRead(string filename)
{
// Added 6/27/2013; adapted from https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
try
{
using (Stream stream = new FileStream(filename, FileMode.Open))
{
try
{
SR = File.OpenText(filename);
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileQuickRead");
}
}
}
catch (Exception exc)
{
// If the "using Stream filename" fails
#if TRACE
UtilCE.LogInfo.Add2LogFile(string.Format("Catch block in FileQuickRead caught: {0}", exc.Message));
#endif
}
}
...日志文件从不包含“Catch Block”字符串,因此它超过了“使用文件名”,但显然在调用 File.OpenText() 时失败了。
此外,它在类中的其他两个方法上也失败了,即 ReadLn 和 FileClose:
public string FileReadLn()
{
try
{
aLine = SR.ReadLine();
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileReadLn");
}
return aLine;
}
public void FileClose()
{
try
{
SR.Close();
}
catch (Exception ex)
{
CCR.ExceptionHandler(ex, "FileQuickRead.FileClose");
}
}
我在 FileQuickRead、FileReadLn 和 FileClose 上连续 3 次收到 NullReferenceException。
类中唯一的另一件事是这些全局声明:
private StreamReader SR;
private string aLine;
调用者以这种方式这样做:
fileQuickRead = new FileQuickRead(fn);
// Read the line from the file*
aLine = fileQuickRead.FileReadLn();
. . .
while ((aLine != null) && (aLine != ""))
. . .
aLine = fileQuickRead.FileReadLn();
if (aLine == null)
continue;
. . .
finally
{
fileQuickRead.FileClose();
}
FileClose() 方法中的 SR.Close() 还不够吗?我需要做些什么来完全刷新文件,还是...???
- 太好了 - 整个项目中唯一的评论,它只泄露了显而易见的东西。