c# - 在 RichTextBox 中用空格链接到文件的路径?

标签 c# winforms hyperlink path richtextbox

我有 VS2010、C#。我在表单中使用 RichTextBox。我将 DectectUrls 属性设置为 True。我设置了一个 LinkClicked 事件。

我想打开这样的文件链接:file://C:\Documents and Settings...file://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) {}
}

有什么建议吗?

最佳答案

您可以使用 UNICODE 不间断空格字符 (U+00A0),而不是使用 %20(某些用户可能会觉得它看起来“丑陋”)。例如:

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);
}

关于c# - 在 RichTextBox 中用空格链接到文件的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157930/

相关文章:

c# - C# : what will happen in this edge case? 中的通用扩展方法

c# - Eval 在代码隐藏中

javascript - 流式传输文档数据后链接无法打开

c# - 如何在winform上绘制丰富格式的字符串?

c# - 以编程方式添加到 FlowLayoutPanel 的项目不像设计时那样对齐

c# - 将 .dll 编译成可执行文件

php - 视频主机链接损坏检查

c# - AS400 C#.net插入新记录问题

电子邮件的 HTML 标签和页面上其他部分的链接

html - 如何创建 "go to page"表单?