2011-06-23 121 views
0

我在我的winform應用程序中有一個按鈕。我希望當用戶點擊這個按鈕時,它會從Visual Studio的c:\ myfile.xml中打開xml文件。現在我不知道用戶所在的位置以及他正在使用哪個版本。 如果這是不可能知道的,那我該如何在記事本中打開它? 我不使用webbrowser進行此任務的原因是因爲用戶需要編輯文件的內容。打開XML文件按鈕

我正在使用c#。

謝謝。

回答

2
string filePath = @"d:\test.xml"; 
//Open in notepad 
System.Diagnostics.Process.Start("notepad", filepath); 
//Open in visual studio 
System.Diagnostics.Process.Start("devenv", filepath); 

注意,當程序可以在PATH環境變量中找到這隻作品中,你必須捕捉異常,並與其他應用程序嘗試......是這樣的:

bool TryStart(string application, string arguments) 
{ 
    try 
    { 
    using (Process.Start(application, arguments)) 
     return true; 
    } 
    catch (Win32Exception) 
    { 
    return false; 
    } 
    catch (FileNotFoundException) 
    { 
    return false; 
    } 
} 

void OpenXml(string filePath) 
{ 
    if (!TryStart("devenv", filePath) && !TryStart("notepad", filePath)) 
     using (Process.Start(filePath)) 
     { } 
} 
+0

完美! !謝謝! –