c# - 错误“该进程无法访问文件'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# 的新手,我希望任何有经验的程序员都知道哪里出了问题。
谢谢你。
解决方案
快速说明:StreamReader 甚至没有被使用。
我想出了一个基本的答案,以替换读取文件行的代码:
List<string> lines = null;
using (var sr = new StreamReader("file.txt"))
{
var text = sr.ReadToEndAsync().Result;
lines = text.Split('\n').ToList();
}
推荐阅读
- python - 根据第一个列表元组值删除两个列表中的相同索引元素
- c# - 在 C# 中验证列表
- python - Django 自定义用户表单:错误:唯一约束失败:auth_user.username
- javascript - 使用带有快照的 ESLint 进行静态分析
- c# - 如何将数据添加到现有行 Sql Server 数据库中
- laravel - 如何在 Laravel 中不使用 url 将变量传递给视图?
- python-3.x - 删除边界框点之间的网格点
- javascript - 节点获取连接 ETIMEDOUT 错误
- javascript - 在 Node 中获取 SQS retrieveMessages 解析
- python - Python 3.6.5 在 'tuple' 和 'str' 错误消息的实例之间返回 '<' not supported