文件在while循环期间被另一个进程使用(c#)
本文关键字:进程 另一个 while 循环 文件 | 更新日期: 2023-09-27 18:02:23
我现在有一个while循环,它包含一个if语句:
if (s.Contains("mp4:production/CATCHUP/"))
虽然当这个条件为真时,我尝试使用其他方法(如下所示,例如RemoveEXELog),我得到一个访问被拒绝的进程当前正在使用文件"Command.bat"
当我执行其他方法时,我怎么能停止循环文件?
private void CheckLog()
{
while (true)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog(); // Deletes a specific keyword from Command.bat
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
ClearLog(); // Deletes Command.bat and then creates a new empty Command.bat
}
}
}
}
}
其他解决方案应该也适用于您,但是,您也可以像这样打开文件:
using (var sr = new FileStream("Command.bat", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
{
...
}
以只读模式打开文件。
然后在你的RemoveEXELog()方法中你可以像这样打开它:
using (var sr = new FileStream("Command.bat", FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite))
{
...
}
这种方法应该允许您从两个位置打开文件,而不会得到文件已被使用的I/O异常。
private void CheckLog()
{
bool _found;
while (true)
{
string s = "";
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
if (_found)
{
RemoveEXELog(); // Deletes a specific keyword from Command.bat
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
ClearLog(); // Deletes Command.bat and then creates a new empty Command.bat
}
}
}
我说的对吗?
RemoveEXELog(); // Deletes a specific keyword from Command.bat
ClearLog(); /
正在处理Command.bat
文件?如果是,必须将它们移出
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
块,因为这个读取器阻止其他程序编辑文件。
尝试使用一些bool标志:
bool needRemove = false, needClear = false;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
needRemove = true;
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
needClear = true;
}
}
}
if (needRemove) RemoveEXELog(); // Deletes a specific keyword from Command.bat
if (needClear) ClearLog(); // Deletes Command.bat and then creates a new empty Command.bat