2010-06-06 52 views
0

我在嘗試複製Impero的策略鎖定屏幕。幫助視覺編程?

我想讓我的程序搜索來查看文件是否存在。這個概念是,如果文件存在,它將被啓動。

使用後臺工作人員搜索它會更好嗎?如果是這樣,我將如何使它搜索它?

關於如何實現所需功能的任何建議?

+6

什麼編程語言和框架?你認爲爲什麼需要一個後臺工作者? – 2010-06-06 02:38:17

+4

此外,對於我們這些從未聽說過「Impero」的人,或者曾經見過他們的政策鎖定屏幕,您應該發佈一個屏幕截圖。 – 2010-06-06 03:33:06

+0

我正在使用基本和這裏的impero的網站 http://www.imperosoftware.com/v2home.asp – tjk0102 2010-06-06 04:06:43

回答

0

由於您沒有指定語言或框架,因此我假定您使用的是C#。你說:

我想讓我的程序搜索,看看文件是否存在。這個概念是,如果文件存在,它將被啓動。

下面是一個簡短的代碼段,它將完成您所要求的操作。

string path = @"C:\path\to\file"; 

if (File.Exists(path)) 
{ 
    Process p = new Process(); 
    p.StartInfo.FileName = path; // launches the default application for this file 
    p.Start(); 
} 

這稍微過於簡單:p.Start()可能由於多種原因而拋出異常。此外,您幾乎無法控制哪個應用程序打開該文件 - 完全取決於用戶的註冊表。例如,如果用戶選擇要打開的HTML文件,則某些用戶將看到使用Internet Explorer打開的文件,而其他用戶將安裝Firefox,因此Firefox將用於查看該文件。

更新:

通常情況下,我搜索使用下列文件:

string[] matches = Directory.GetFiles(@"C:\", "*.txt"); 

它返回所有路徑的C:\驅動與.txt結束上的所有文件。當然,你的搜索模式會有所不同。

如果對Directory.GetFiles()的調用(或者您使用的任何 - 您沒有指定的)需要很長時間,那麼使用BackgroundWorker是一個好方法。你可以這樣做。在類的構造函數(你可以選擇把它SearchFiles):

string searchPattern; 
string searchDirectory; 

BackgroundWorker worker; 

string[] matches; 

/// <summary> 
/// Constructs a new SearchFiles object. 
/// </summary> 
public SearchFiles(string pattern, string directory) 
{ 
     searchPattern = pattern; 
     searchDirectory = directory; 

     worker = new BackgroundWorker(); 
     worker.DoWork += FindFiles; 
     worker.RunWorkerCompleted += FindFilesCompleted; 

     worker.RunWorkerAsync(); 
} 

void FindFilesCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
     if (e.Error == null) 
     { 
     // matches should contain all the 'found' files. 

     // you should fire an event to notify the caller of the results 
     } 
} 


void FindFiles(object sender, DoWorkEventArgs e) 
{ 
     // this is the code that takes a long time to execute, so it's 
     // in the DoWork event handler. 
     matches = System.IO.Directory.GetFiles(searchDirectory,searchPattern); 
} 

我希望這回答您的問題!

+0

等等。那實際上並不是完整的腳本? – tjk0102 2010-06-06 13:29:32

+0

以及如何讓它在實際打開程序之前在後臺搜索文件? – tjk0102 2010-06-06 14:00:10

+0

我已更新我的答案,以提供有關搜索文件的更多信息。我在你的評論中看到你說過你使用「基本」。你的意思是* Visual * Basic? MSDN BackgroundWorker頁面:http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx有3種語言的示例;語法是不同的,但概念都是一樣的。 – 2010-06-06 16:11:43