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

时间:2019-05-22 14:03:35

标签: c# visual-studio

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

我知道游戏正在使用聊天记录,但是正如我所说,我可以读取行数,甚至可以在达到1000行后删除整个文本,直到出现错误为止。我还可以手动编辑文件并在游戏中保存。

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#的新手,我希望任何有经验的程序员都知道出什么问题了。

谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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