Link to File's path with spaces in RichTextBox? - c#

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?

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

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 \".

go to that particular folder and give the permission to write or make it shared from properties of that folder.

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

Related

C# How to fix this code from multi-line text to label on marquee text moving right to left?

I made a program that text is moving right to left(marquee).
But, I can't make use multi-line text to label.
Who can help me?
single line text is good work. But if multi-line, just get last sentence.
private void timer1_Tick(object sender, EventArgs e)
{
string screentext = clsBas.SCREEN_TEXT;//include in Multi-line text;
string[] result = screentext.Split(new string[] { "\r\n" }, StringSplitOptions.None);
string space = " ";
foreach (string news in result)
{
lblScreenText.Text = news + space;
if (lblScreenText.Left < 0 && (Math.Abs(lblScreenText.Left) >
lblScreenText.Width))
lblScreenText.Left = lblScreenText.Width;
lblScreenText.Left -= 2;
}
}
Try using Environment.NewLine and append to text.
Better way to do it, is to use textbox multi-line and make it read-only.

For some reason when an input string is has no value, it still shows the previous input also i can't get to the next line in the textbox

So I made this code that when key words are typed into the first text box ("TextEditor") it should give an output to another text box ("output"). So there are two moderately simple problems that I have no clue how to fix. (1) when you write one keyword in the TextEditor the proper output i shown. But when you write the other keyword that would be expected the out that was given for keyword number 1 is deleted and the output for keyword 2 is shown. It is supposed to show both keyword outputs but on separate lines. My second problem is I can't figure out how to make output (the second textbox) to have no output when there is no input in TextEditor After a keyword is written but then deleted.
So if I wrote: "create" output would show "Token: CREATE" but then if I wrote "Variable" after the "create" the output text would change from "Token: CREATE" to "Token: VARIABLE". I need the out put of both to be on separate lines so they don't cancel each other out. Now if I deleted whatever I had earlier, The output text would still show "Token: Variable" instead of having a blank textbox. Here is my code:
private void TextEditor_TextChanged(object sender, EventArgs e)
{
string input = TextEditor.Text;
if (input != " ")
{
string[] command = { "create", "if" };
if (input.ToLower().Contains(command[0]))
{
Output.Text = "Token: CREATE";
string[] type = { "variable", "boolean" };
if (input.ToLower().Contains(type[0]))
{
Output.Text = "Token: VARIABLE";
Output.AppendText(Environment.NewLine); //this is supposed to change to the next line but for some reason it doesnt.
string[] variable = { "value", "called" };
if (input.ToLower().Contains(variable[0]))
{
Output.Text = "Token: VALUE";
}
}
}
}
else
{
Output.Text = " ";
}
Well what you are doing is resetting your text variable to say either create or variable with =. You could just append += to your text variable rather then assigning it again. I just use \n to create newline, and append it to the text output. Not sure what you are writing this in I assumed wpf and it didn't seem to like the Environment.NewLine so I just got rid of it.
string input = TextEditor.Text;
if (input != " ")
{
string[] command = { "create", "if" };
if (input.ToLower().Contains(command[0]))
{
Output.Text = "Token: CREATE";
string[] type = { "variable", "boolean" };
if (input.ToLower().Contains(type[0]))
{
Output.Text += "\nToken: VARIABLE";
// Output. AppendText(Environment.NewLine); //this is supposed to change to the next line but for some reason it doesnt.
string[] variable = { "value", "called" };
if (input.ToLower().Contains(variable[0]))
{
Output.Text += "\nToken: VALUE";
}
}
}
}
else
{
Output.Text = " ";
}

How do I add a new line to a richtextbox without making the last line blank?

I'm making a log system for a program im creating and I currently have it to where it does this:
void outToLog(string output)
{
logRichTextBox.AppendText(output + "\r\n");
logRichTextBox.ScrollToCaret();
}
But it ends up outputting the last line of the RichTextBox as blank (because I'm using \n) and I want the last line to just be whatever the output was, not a blank line. An alternative was for me to put the "\r\n" at the beginning, but this just has the same affect except its at the beginning of the RichTextBox.
help? thanks
Append the text after the newline.
void outToLog(string output)
{
logRichTextBox.AppendText("\r\n" + output);
logRichTextBox.ScrollToCaret();
}
If you don't want the newline at the start, check the TextBox for empty text and only add the \r\n when the TextBox is not empty.
void outToLog(string output)
{
if(!string.IsNullOrWhiteSpace(logRichTextBox.Text))
{
logRichTextBox.AppendText("\r\n" + output);
}
else
{
logRichTextBox.AppendText(output);
}
logRichTextBox.ScrollToCaret();
}
Eh, why not check? If text box is empty - just put the output, but if text box is not empty, add a new line and then append the the output.
void outToLog(string output)
{
if (String.IsNullOrEmpty(logRichTextBox.Text))
logRichTextBox.AppendText(output);
else
logRichTextBox.AppendText(Environment.NewLine + output);
logRichTextBox.ScrollToCaret();
}

C# remove unallowed folder name characters [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How check if given string is legal (allowed) file name under Windows?
I have searched about, spent some minutes googling, but i cant apply what i have found, to my context..
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string fname = projectNameBox.Text;
if (projectNameBox.TextLength != 0)
{
File.Create(appPath + "\\projects\\" + fname + ".wtsprn");
So, i am retrieving the projectNameBox.Text and creating a file with the text as filename, but if i include a :, or a \ or a / etc.. it will just crash, which is normal, as those are not allowed for a folder name..How can i check the text, before the file creation, and remove the characters, or even better, do nothing and advise the user that he can not use those characters?
Thanks in advance
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string fname = projectNameBox.Text;
bool _isValid = true;
foreach (char c in Path.GetInvalidFileNameChars())
{
if (projectNameBox.Text.Contains(c))
{
_isValid = false;
break;
}
}
if (!string.IsNullOrEmpty(projectNameBox.Text) && _isValid)
{
File.Create(appPath + "\\projects\\" + fname + ".wtsprn");
}
else
{
MessageBox.Show("Invalid file name.", "Error");
}
Alternative there is a regex example in the link provided in the first comment.
You can respond to the TextChanged event from your projectNameBox TextBox to intercept changes made to its contents. This means that you can remove all the invalid characters before creating your path later on.
To create the event handler, click on your projectNameBox control in the designer, click the Events icon in the Properties window, then double-click on the TextChanged event in the list that appears below. The following is a brief example of some code that strips out invalid characters:
private void projectNameBox_TextChanged(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
string invalid = new string(System.IO.Path.GetInvalidFileNameChars());
Regex rex = new Regex("[" + Regex.Escape(invalid) + "]");
textbox.Text = rex.Replace(textbox.Text, "");
}
(You'll need a using statement for System.Text.RegularExpressions at the top of your file, too.)

Output text in text box not multi-line, word wrap set to true in text box property

I need the text box to my winform to be multi-line but I can't figure out how to do it. It just comes out as one line. Word wrap is set to true. Do I also have to set it to true within my code? Have I screwed up my formatting somehow? I'm not sure what I am doing wrong. Here is the code:
public override string ToString()
{
return string.Format("{0} Pizzas # {1:C}: {2:C}\n" +
"{3} Cokes # {4:C} {5:C}\n" +
"Order Amount: {6:C}\n" +
"Sales Tax: {7:C}\n" +
"Amount Due: {8:C}\n" +
"Amount Paid: {9:C}\n" +
"Change Due: {10:C}", numberOfPizzas, PIZZA_PRICE,
totalCostOfPizza, numberOfCokes, COKE_PRICE, totalCostOfCoke,
foodAndDrinkTotal, totalSalesTax, totalAmountDue, amountPaid,
changeDue);
}
........
private void btnPaymentButton_Click(object sender, EventArgs e)
{
amountPaid = double.Parse(this.txtAmountPaid.Text);
orderPaymentObject = new Payment(orderObject.TotalAmountDue, amountPaid);
this.txtNumberOfPizzaOrdered.Clear();
this.txtNumberOfCokesOrdered.Clear();
this.txtAmountDue.Clear();
this.txtAmountPaid.Clear();
this.lblYourOrder.Visible = true;
this.txtYourOrder.Visible = true;
this.txtYourOrder.Text = orderObject.ToString();
}
In windows you need both a carriage return \r and a line feed \n to get a newline. So in your example above you would need to change every \n into a \r\n.
Also, you may not have set the Multiline property.
Try using a RichTextBox instead of a Textbox

Categories

Resources