【问题标题】:Error "The process cannot access the file 'fileDir' because it is being used by another process." while trying to read or write a text file [duplicate]错误“该进程无法访问文件'fileDir',因为它正被另一个进程使用。”尝试读取或写入文本文件时[重复]
【发布时间】:2019-05-22 14:03:34
【问题描述】:

我正在编写一个应用程序来读取游戏的聊天记录。问题是我随机收到一个错误,也许应用程序工作了 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# 的新手,我希望任何有经验的程序员都知道哪里出了问题。

谢谢。

【问题讨论】:

  • 你为什么还要创建StreamReaders?你永远不会使用它们......
  • 好吧,我觉得自己很蠢。
  • 您的问题几乎肯定是上面列出的@Çöđěxěŕ - 在您尝试访问时文件被锁定。这是另一个既解决了该问题又解决了您尝试的文件轮询的问题。 Reading file content changes in net
  • 我阅读了所有内容,但我不明白:s

标签: c# visual-studio


【解决方案1】:

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

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

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

【讨论】:

  • 那么,如果行数高于 1000,我应该如何编写代码来删除文本文件内容而不会出现该错误?我应该在 using 中添加 stramwritter 还是新建一个?
  • @Arkshija 所以如果文件的行数超过 1000 行,您想删除所有行还是只删除超过 1000 行的行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多