使用Do while循环来检查文件是否存在

3
我正在为我工作的公司编写一个C#程序,该程序将启动一个创建PDF文件并打开PDF文件的PHP脚本。目前,我的代码如下:
// launch the PHP page to generate my pdf report
Process.Start(phpFile);

// wait for the report to exist
Thread.Sleep(waitTime);

// open the report
Process.Start(filePath);

现在,我不喜欢整个 "Sleep() 指定时间,希望文件存在时再执行" 的做法。所以我的问题是,是否可行/更好的方法是使用 do 循环并说:

do
{
    // Do nothing until the file exists 
} while (!File.Exists(filePath));
5个回答

8

2
我喜欢这种方法。但正如其他评论中有人所说,它会等待PDF完全编写好再打开,还是可能在此之前尝试打开呢? - PiousVenom
好问题...我认为一旦文件到位,它就会触发事件。如果是这种情况,那么Sean的答案将是解决方案。 - Frederik Gheysels
我使用了这个进行测试,效果非常好。非常感谢。 - PiousVenom

6
使用 File.Exists 的问题在于该文件可能在第一个进程完成写入之前就已经存在。我建议改用以下方法:
// launch the PHP page to generate my pdf report
Process generator = Process.Start(phpFile);

// wait for the report to exist
generator.WaitForExit();

// open the report
Process.Start(filePath);

4
使用FileSystemWatcher并处理创建事件。如果您希望它同步发生,请使用带有超时的FileSystemWatcher.WaitForChanged

0

等待第一个进程结束怎么样?

Process p = Process.Start(phpFile);
p.WaitForExit();

Process.Start(filePath);

0

我认为更好的方法是以任何方式查看文件是否存在。如果您依赖于固定的时间量,它可能会失败或进程将等待比所需时间更长。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接