执行while循环以检查文件是否存在

Pio*_*nom 3 c# loops

我正在为我工​​作的公司编写一个C#程序,它将启动一个创建PDF的PHP脚本,然后打开PDF文件.现在,我有:

// 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);
Run Code Online (Sandbox Code Playgroud)

现在,我不是一个整体的粉丝" Sleep()在指定的时间内希望文件存在时完成".所以我的问题是,使用do循环是否可行/更好并说:

do
{
    // Do nothing until the file exists 
} while (!File.Exists(filePath));
Run Code Online (Sandbox Code Playgroud)

Fre*_*els 8

为什么不使用FileSystemWatcher

设置PathFilter属性并订阅Created事件.

  • 我喜欢这种方法.但正如有人在另一条评论中所述,这会等到PDF完全写完,还是有可能会尝试先打开它? (2认同)

Sea*_*ght 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);
Run Code Online (Sandbox Code Playgroud)