如何防止我的文件被其他进程使用?

时间:2014-12-11 22:02:31

标签: c# file-io process filestream

这是问题here的续集,我想知道为什么我的流不可用。

利用一些回答其他问题的猫的想法,我现在得到了这段代码:

private readonly FileStream _fileStream;
private readonly StreamWriter _streamWriter;

. . .

private ExceptionLoggingService()
{
    const int MAX_LINES_DESIRED = 1000;
    int linesInLogFile;

    string uriPath = GetExecutionFolder() + "\\Application.log";
    string logPath = new Uri(uriPath).LocalPath;
    _fileStream = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
    StreamReader _streamReader = new StreamReader(_fileStream);
    List<String> logList = new List<String>();

    while (!_streamReader.EndOfStream)
    {
        logList.Add(_streamReader.ReadLine());
    }
    linesInLogFile = logList.Count;
    while (logList.Count > MAX_LINES_DESIRED)
    {
        logList.RemoveAt(0);
    }

    if (linesInLogFile > MAX_LINES_DESIRED)
    {
        _fileStream.Close();
        File.Delete(logPath);
        File.Create(logPath);
        _fileStream.Close(); // added this; did not help
        _fileStream.Dispose(); // this also did no good
        _fileStream = File.OpenWrite(logPath); // <= exception occurs here
    }

    _streamWriter = new StreamWriter(_fileStream);

    foreach (String s in logList)
    {
        _streamWriter.WriteLine(s);
    }
    _streamWriter.Flush(); // here is okay, right (as opposed to within the foreach loop)?
}

...但是在指示的(“OpenWrite()”)行上我得到以下异常(我在它上面添加了两行,首先是对Close()的调用,然后是Dispose(),但异常仍然是相同):

System.IO.IOException was unhandled
  _HResult=-2147024864
  _message=The process cannot access the file 'C:\HoldingTank\Sandbox\bin\Debug\Application.log' because it is being used by another process.

因此,如果Close没有关闭_fileStream,并且Dispose没有处理它,可以做什么?

更新

这并没有严格回答我的问题,但它的确有效,受劳埃德评论的启发:

const int MAX_FILESIZE_ALLOWED = 20000;
string uriPath = GetExecutionFolder() + "\\Application.log";
string logPath = new Uri(uriPath).LocalPath;
FileInfo f = new FileInfo(logPath);
long fileLenInBytes = f.Length;
if (fileLenInBytes > MAX_FILESIZE_ALLOWED)
{
    File.Delete(logPath);
}
_fileStream = File.OpenWrite(logPath);
_streamWriter = new StreamWriter(_fileStream);

1 个答案:

答案 0 :(得分:2)

您可以使用FileShare枚举之一,例如:

_fileStream = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

您可以使用FileShare.None锁定文件,如MSDN:

中所述
  

拒绝分享当前文件。任何打开文件的请求(通过   在文件关闭之前,此过程或其他过程将失败。

但是,因为这是日志记录,我建议您使用NLogLog4Net之类的东西,而不是自己滚动,让它处理日志输出。