是否存在关闭/释放文件的“核选项”?

时间:2013-06-28 18:59:13

标签: c# file file-io io nullreferenceexception

我在这里的原始相关问题(https://stackoverflow.com/questions/17332403/is-there-such-a-c-sharp-method-or-methodology-that-would-equate-to-filealready)被标记为重复,我使用了假定的副本 (Is there a way to check if a file is in use?)试图解决我的问题,但我仍然在某些文件I / O操作上充斥着空引用异常。

根据以前的宁静帖子,我改变了以前的代码:

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”字符串,因此它已超过“using filename”,但显然在调用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上连续三次得到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()不够用吗?我是否需要做一些事情才能完全刷新文件,或者...... ???

  • 很棒 - 整个项目中唯一的评论,它只是泄露了显而易见的明显。

0 个答案:

没有答案