Dan*_*986 4 c# load file delete-file
我在我的应用程序中遇到此问题:
我的第一个问题是这部分代码:
XmlDocument xmlDoc = new XmlDocument();
DataSet ds = //use a method to put in the data
xmlDoc.LoadXml(ds.GetXml());
xmlDoc.Save("Filename");
// ...
Process.Start(startInfo);
Run Code Online (Sandbox Code Playgroud)
我的假设是否正确,只有在完成上述操作后才会执行最后一行?所以我可以100%确定数据是否都在xml中,然后才能尝试启动它?
我现在收到错误的第二部分是:
Process.Start(startInfo);
File.Delete("Filename");
Run Code Online (Sandbox Code Playgroud)
现在发生的事情是,在第三方程序将文件读入其内存之前,该文件已被删除.
有什么方法可以检查文件不再使用,或者做一些稳定的等待方式?
我已经找到了一种使用方法,Thread.Sleep(TimeInMiliSec);但我想这不是一种正确的方法(更像是一种解决方案)?
您可以在我的示例中使用该方法并执行while循环.
while (IsFileLocked(new FileInfo("YourFilePath")))
{
// do something, for example wait a second
Thread.Sleep(TimeSpan.FromSeconds(1));
}
// file is not locked
public static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
看起来您只需要添加如下内容:
Process p = new Process();
p.StartInfo = startInfo;
p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
Process.Start() 启动另一个进程,但它不会等待该进程完成后再继续。
| 归档时间: |
|
| 查看次数: |
10313 次 |
| 最近记录: |