我目前有一个 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 异常。
关于c# - 在 while 循环期间文件正在被另一个进程使用 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6719773/