2013-03-01 59 views
3

我有VS2010,C#。我在表單中使用RichTextBox。我將DectectUrls屬性設置爲True。我設置了一個LinkClicked事件。用RichTextBox中的空格鏈接到文件路徑?

我想開這樣的文件鏈接:文件:// C:\ Documents和Settings ...文件:// C:\ Program Files文件(x86)的...

它不適用於帶空格的路徑。

的源代碼:

rtbLog.SelectionFont = fnormal; 
rtbLog.AppendText("\t. Open Path" + "file://" + PathAbsScript + "\n\n"); 


// DetectUrls set to true 
// launch any http:// or mailto: links clicked in the body of the rich text box 
private void rtbLog_LinkClicked(object sender, LinkClickedEventArgs e) 
{ 
    try 
    { 
     System.Diagnostics.Process.Start(e.LinkText); 
    } 
    catch (Exception) {} 
} 

有什麼建議?

+1

你應該用雙引號路徑('「文件:// c:\ path with spaces \ ...「) – 2013-03-01 12:40:34

回答

1

最後,我用一個取代(」」, 「%20」)

// http://social.msdn.microsoft.com/Forums/eu/Vsexpressvb/thread/addc7b0e-e1fd-43f4-b19c-65a5d88f739c 
var rutaScript = DatosDeEjecucion.PathAbsScript; 
if (rutaScript.Contains(" ")) rutaScript = "file://" + Path.GetDirectoryName(DatosDeEjecucion.PathAbsScript).Replace(" ", "%20"); 
rtbLog.AppendText(". Abrir ubicación: " + rutaScript + "\n\n"); 

爲LinkClicked事件中的代碼:

private void rtbLog_LinkClicked(object sender, LinkClickedEventArgs e) 
{ 
      try 
      { 
       var link = e.LinkText.Replace("%20", " "); 
       System.Diagnostics.Process.Start(link); 
      } 
      catch (Exception) 
      { 
      } 
} 
2

你應該用雙引號的路徑,例如:

"file://c:\path with spaces\..." 

,向雙引號添加到字符串,則必須使用轉義序列\"

1

轉到該特定文件夾,並授予寫入權限或使其從該文件夾的屬性共享。

3

使用%20(而不是一些用戶可能會發現「醜」看),你可以使用UNICODE不間斷空格字符(U + 00A0)。例如:

String fileName = "File name with spaces.txt"; 
FileInfo fi = new FileInfo(fileName); 

// Replace any ' ' characters with unicode non-breaking space characters: 
richTextBox.AppendText("file://" + fi.FullName.Replace(' ', (char)160)); 

然後爲豐富文本框中輸入鏈接點擊處理程序中,你會做到以下幾點:

private void richTextBox_LinkClicked(object sender, LinkClickedEventArgs e) 
{ 
    // Replace any unicode non-break space characters with ' ' characters: 
    string linkText = e.LinkText.Replace((char)160, ' '); 

    // For some reason rich text boxes strip off the 
    // trailing ')' character for URL's which end in a 
    // ')' character, so if we had a '(' opening bracket 
    // but no ')' closing bracket, we'll assume there was 
    // meant to be one at the end and add it back on. This 
    // problem is commonly encountered with wikipedia links! 

    if((linkText.IndexOf('(') > -1) && (linkText.IndexOf(')') == -1)) 
     linkText += ")"; 

    System.Diagnostics.Process.Start(linkText); 
} 
+0

感謝您的支持。我必須將路徑放在引號中才能使其正常工作。但後來它罰款... :-) – jreichert 2016-02-16 10:43:51

+0

嗯。看來,dyImcc的解決方案只適用於Windows Vista或更高版本。在傳統的Windows XP上,它不適用於我,我必須使用醜陋的空格「%20」(這裏不需要引號)。 – jreichert 2016-02-16 11:30:43