链接到文件'的路径与RichTextBox中的空格

本文关键字:路径 空格 RichTextBox 文件 链接 | 更新日期: 2023-09-27 18:01:48

我有VS2010, c#。我使用RichTextBox的形式。我将DectectUrls属性设置为True。我设置了一个LinkClicked事件

我想打开这样一个文件链接:file://C:'Documents and Settings…文件://C: '程序文件(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) {}
}

有什么建议吗?

链接到文件'的路径与RichTextBox中的空格

不要使用%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);
}

你应该用双引号把路径括起来,例如:

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

要在字符串中添加双引号,必须使用转义序列'"

进入该特定文件夹,并从该文件夹的属性中授予写入或共享权限。

最后,我使用一个替代(","% 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)
            {
            }
}