问题
I have VS2010, C#. I use RichTextBox in a form. I set the DectectUrls property to True. I set a LinkClicked event.
I would like open a file link like this: file://C:\Documents and Settings... or file://C:\Program Files (x86)...
It doesn't works for path with spaces.
The source code:
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) {}
}
Any suggestions?
回答1:
Instead of using %20 (which some users may find "ugly" looking), you can use the UNICODE non-breaking space character (U+00A0). For example:
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));
Then inside your link click handler for the rich text box, you'd do the following:
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);
}
回答2:
You should enclose the path with double quotes, e.g.:
"file://c:\path with spaces\..."
To add a double quote to a string, you must use an escape sequence \"
.
回答3:
go to that particular folder and give the permission to write or make it shared from properties of that folder.
回答4:
Finally, I use a replace (" ", "%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");
The code for LinkClicked event:
private void rtbLog_LinkClicked(object sender, LinkClickedEventArgs e)
{
try
{
var link = e.LinkText.Replace("%20", " ");
System.Diagnostics.Process.Start(link);
}
catch (Exception)
{
}
}
来源:https://stackoverflow.com/questions/15157930/link-to-files-path-with-spaces-in-richtextbox