首页 > 解决方案 > 错误“该进程无法访问文件'fileDir',因为它正被另一个进程使用。” 在尝试读取或写入文本文件时

问题描述

我正在编写一个应用程序来读取游戏的聊天记录。问题是我随机收到一个错误,也许应用程序工作了 20 分钟或 30 分钟,然后突然收到错误:System.IO.IOException:“进程无法访问文件'fileDir',因为它正在被另一个进程使用。”

我知道游戏正在使用聊天日志,但正如我所说,我可以在达到 1,000 行后毫无问题地阅读这些行甚至删除整个文本,直到我得到那个错误。我也可以手动编辑文件并在游戏中保存。

private void start_Click(object sender, EventArgs e){
      if (!_isRunning)
      {        
          _isRunning = true;                     
          StreamReader sr = new StreamReader(fileDir);
          var lines = File.ReadAllLines(fileDir);
          lastReadLine = lines.Length - 1; //start to read from the last line 
          sr.Close();                   
          timer1.Start();
      }
}  
private void UpdateText()
{
    try
    {
        StreamReader sr = new StreamReader(fileDir); // error here
        var lines = File.ReadAllLines(fileDir);
        sr.Close();
        linesLength = lines.Length;
        for (int i = lastReadLine; i < lines.Length; i++)
        {
            if (lines[i].Contains("You inflicted") || lines[i].Contains("The attack missed") || lines[i].Contains("The target Dodged"))
            {
                totalAttacks++; 
            }
            lastReadLine = i + 1;
        }

        if (linesLength >= linesMax)
        {
            try
            {
                if (File.Exists(fileDir))
                {
                    TextWriter tw = new StreamWriter(fileDir, false); //error here 1 time
                    lastReadLine = 0;
                    tw.Close();
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

计时器每秒执行 1 次 UpdateText()。这是我第一个使用 Visual Studio 的应用程序,我也是 C# 的新手,我希望任何有经验的程序员都知道哪里出了问题。

谢谢你。

标签: c#visual-studio

解决方案


快速说明:StreamReader 甚至没有被使用。

我想出了一个基本的答案,以替换读取文件行的​​代码:

List<string> lines = null;
using (var sr = new StreamReader("file.txt"))
{
    var text = sr.ReadToEndAsync().Result;
    lines = text.Split('\n').ToList();
}

推荐阅读