我目前有一个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
}
}
}
}
}
答案 0 :(得分:3)
其他解决方案应该适合您,但是,您也可以这样打开文件:
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异常。
答案 1 :(得分:1)
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
}
}
}
答案 2 :(得分:0)
我的代码是否正确:
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