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

本文关键字:进程 其他 何防止 我的 文件 | 更新日期: 2023-09-27 18:34:08

这是这里问题的续集,我想知道为什么我的流无法涉足。

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

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.

因此,如果"关闭"不关闭_fileStream,并且"处置"不处置它,该怎么办?

更新

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

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);

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

可以使用文件共享枚举之一,例如:

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

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

拒绝共享当前文件。任何打开文件的请求(通过 此过程或其他进程)将失败,直到文件关闭。

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