2011-10-27 45 views
2

我創建了一個使用特定文件類型的程序,並將該文件類型與該程序關聯,但是當我單擊該文件時,它只啓動該程序,但它沒有加載我點擊的文件。我怎樣才能讓我的程序加載文件?打開文件並加載它

回答

1

您可以使用static void Main(string[] args)來獲取文件名。

我會做這樣的事情:

地方在你的代碼,你應該有一個字符串變量在哪裏存儲檢索到的文件名private string filename;

static void Main(string[] args) { 
    // first check if there are arguments 
    if (args.length > 0) 
    { 
    // check if the filename has the right extension 
    if (args[0].EndsWith(".ext")) 
    { 
     // check for existence 
     if (System.IO.File.Exists(args[0])) 
     { 
      // it exists.. so store the filename in the previously defined variable 
      filename = args[0]; 
     } 
    } 
    } 
} 

這樣你就可以做一種邏輯的時候當文件名變量沒有時,文件名變量有內容和另一種邏輯。

希望你能用這個。

2

在您的應用程序中,您必須使用Main(string[] args)並從傳遞到應用程序的args參數中獲取。
這是一個例子:

static void Main(string[] args) 
{ 
    if (args.Length == 0) return; 
    string text = File.ReadAllText(args[0]); 
} 
+0

...我想你需要在你的Windows文件關聯中指定參數,如下所示:http://technet.microsoft.com/en-us/library/cc749986.aspx – zoidbeck

+0

@zoidbeck:yes,但是OP告訴我們他的應用程序在雙擊目標文件時打開,所以我認爲這已經OK – Marco

+0

好吧,還沒有試過,並認爲這個'%1'作爲參數必須明確設置。很高興知道...或作爲upvotes似乎表明你必須明確地設置它來獲得它或使用環境:-) – zoidbeck

3

當你打開你與應用程序相關的文件,該文件的路徑傳遞到你的程序的命令行參數。您可以自己加載文件,如下所示:

string fileName = Environment.GetCommandLineArgs()[0];