2014-10-09 46 views
0

我已經看過 Is there a way to check if a file is in use?How to wait until File.Exists?睡到文件存在/參考創建

但我想避免使用SystemWatcher,因爲它似乎有點過分的。我的應用程序調用cmd提示符來創建一個文件,因爲我的應用程序沒有辦法知道它何時完成,所以我一直在考慮使用Sleep(),只要該文件不存在。

string filename = @"PathToFile\file.exe"; 
int counter = 0; 
while(!File.Exists(filename)) 
{ 
    System.Threading.Thread.Sleep(1000); 
    if(++counter == 60000) 
    { 
     Logger("Application timeout; app_boxed could not be created; try again"); 
     System.Environment.Exit(0); 
    } 
} 

不知何故,我的這段代碼似乎不工作。可能是什麼原因?

+12

我保證'SystemWatcher'將使用較少的資源,那麼你拿出包括睡眠和而任何方法循環 – Icemanind 2014-10-09 19:05:12

+3

這聽起來像是'FileSystemWatcher'的確切目的*。如果你寫的代碼不起作用,並且'FileSystemWatcher'確實起作用,那麼它並不是真的「過度」。 – David 2014-10-09 19:06:39

+2

會發生什麼? _似乎不工作_太模糊。 – Steve 2014-10-09 19:06:46

回答

3

不確定哪部分不能正常工作。你是否意識到你的循環將運行60,000秒(16.67小時)?您每秒一次遞增,並等待它達到60000

嘗試是這樣的:

const string filename = @"D:\Public\Temp\temp.txt"; 

// Set timeout to the time you want to quit (one minute from now) 
var timeout = DateTime.Now.Add(TimeSpan.FromMinutes(1)); 

while (!File.Exists(filename)) 
{ 
    if (DateTime.Now > timeout) 
    { 
     Logger("Application timeout; app_boxed could not be created; try again"); 
     Environment.Exit(0); 
    } 

    Thread.Sleep(TimeSpan.FromSeconds(1)); 
} 
+0

不錯我喜歡你的代碼比我的更多。我在時間上犯了一個錯誤,並糾正了代碼的其他部分,所以現在可以工作。 – sceiler 2014-10-09 21:32:06