Problems with reading text and display in textboxs in c# - c#

My intention is using File.ReadAllText to read a text file line by line. After that, I will check each string array if it contains the keyword that I expected, I will take the whole string out and display it into a textbox. So here is my code :
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text = readline[i].Substring(2, len - 4);
textBox3.AppendText(Environment.NewLine);
}
}
The problem is : if the input file look like
<>something<>
<>something1<>
<>something2<>
<>something3CPL<>
<>something4CPL<>
<>something5CPL<>
The output is always just the last string array. (here is something5CPL).
What I expected is
something3CPL
something4CPL
something5CPL
Can anybody tell me what is wrong with my code?
Thank you.

You're assigning (overwriting) the text in the textbox each iteration, so it'll only hold the last value you get from the file:
textBox3.Text = readline[i].Substring(2, len - 4);
Instead, use the same technique (appending) as you did with the Environment.Newline:
textBox3.AppendText(readline[i].Substring(2, len - 4));
This will keep adding the new values onto the end of the textbox's existing text, as you want.

You need to append the text each instead of setting the text in each iteration:
textBox3.AppendText(readline[i].Substring(2, len - 4));

May be in place of
textBox3.Text = readline[i].Substring(2, len - 4);
use
textBox3.Text += readline[i].Substring(2, len - 4);

As a textbox you can't see the results vertically.
Anyway this is the solution:
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text += (readline[i].Substring(2, len - 4) + " ");
}
}

Related

Remove characters before character “|”

I have a software which needs to remove all of the characters before "|".
For example input
" text needs to removed | Text needs to stay "
An example output will be
"Text needs to stay"
I have the code down below. It works for single-line text but doesn't work on multiple lines. (only removes the text on the first line rest of them stays the same)
I need to make it work with multiple lines. Any ideas?
string input = richTextBox.Text;
string output = input.Substring(input.IndexOf('|') + 1);
richTextBox1.Text = output;
You could do it easily using the Lines property and a temporary List<string> to store the result of substring
List<string> newLines = new List<string>();
foreach (string s in richTextBox1.Lines)
{
// If you want only the lines with the | remove the else block
int x = s.IndexOf('|');
if(x > -1)
newLines.Add(s.Substring(x + 1).Trim());
else
newLines.Add(s);
}
richTextBox1.Lines = newLines.ToArray();
string output = "";
var myArray = input.Split("\r\n");
foreach(var ar in myArray)
if(ar.Length > 0)
output+= ar.Substring(0, ar.IndexOf('|')) + "\r\n";
Oups! i returned the first part, but i suppose you got the point
What about using LINQ for this.
E.g.:
List<string> lines = yourString.Split("\n"); //Add \r if needed
List<string> smallerLines = lines.Select(x => x.Skip(x.IndexOf('|')+1));
If needed you can always create one new string of the output:
string finalString = String.Join(String.Empty, smallerLines);
string input = richTextBox1.Text;
int len = richTextBox1.Lines.Length;
string output = "";
for (int i = 0; i <len; i++)
{
if(i!=len-1)
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1) +
Environment.NewLine;
}
else
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1);
}
}
richTextBox1.Text = output;

C# losing Font Style in RichTextBox after deleting lines

I have a RichTextBox for a simple chat where I add lines programmatically.
I make the usernames bold and the messages in regular style.
After some lines I want to delete the first lines to keep the chat in a acceptably length. But when I do so I lose the text format and everything appears bold. What am I doing wrong and how can I fix this?
EDIT
I could solve the problem where I wasn't able to delete the first line.
I had to set the the ReadOnly property to false. Even though I was able to add new lines it prevented deleting lines. So the following code works to delete lines. Thanks to #TaW!
if (ChatText.Lines.Length >= 10)
{
int p = 0; int count = 0;
do
{
p = ChatText.Text.IndexOf("\n\r");
if (p >= 0)
{
ChatText.SelectionStart = p;
ChatText.SelectionLength = 2; // length of "\n\r"
ChatText.SelectedText = "\n";
count++;
}
}
while(p >= 0);
int nll = 1; // <<=== pick the length of your new line character(s)!!
int pS = ChatText.Lines.Take(0).Select(x => x.Length + nll).Sum() - nll;
int pL = ChatText.Lines.Take(1).Select(x => x.Length + nll).Sum() - nll;
if (pS < 0) { pS = 0; pL++; }
ChatText.SelectionStart = pS;
ChatText.SelectionLength = pL - pS;
ChatText.Cut();
}
//////////////////////////////////
// now add new lines
//////////////////////////////////
string[] chatstr;
// string text is given as method parameter
chatstr = text.Split(new string[] { ": " }, 2, StringSplitOptions.None);
// go to the end of the text
ChatText.SelectionStart = ChatText.Text.Length;
ChatText.SelectionLength = 0;
// make text bold
ChatText.SelectionFont = new Font(ChatText.Font, FontStyle.Bold);
// add username (chatstr[0]) and colon
ChatText.AppendText(chatstr[0] + ": ");
// make text regular
ChatText.SelectionFont = new Font(ChatText.Font, FontStyle.Regular);
// add message (chatstr[1])
ChatText.AppendText(chatstr[1] + "\n");
// and finaly scroll down
ChatText.ScrollToCaret();
So deleting lines works and new lines are added as intended. Finaly!
solved :)
Never change the Text of a RichtTextBox if it contains any formatting.
Changing the Lines property (by Skip) is just another way to change the Text.
Instead only use the functions the RTB provides: Always start by selecting the portion you want to format, then apply one or more of the functions and/or set one or more of the properties..:
To delete portions use Cut.
Here is a function that will delete a number of entire lines:
void DeleteLines(RichTextBox rtb, int fromLine, int count)
{
int p1 = rtb.GetFirstCharIndexFromLine(fromLine);
int p2 = rtb.GetFirstCharIndexFromLine(fromLine + count);
rtb.SelectionStart = p1;
rtb.SelectionLength = p2 - p1;
bool readOnly = rtb.ReadOnly; // allow change even when the RTB is readonly
rtb.ReadOnly = false; ;
rtb.Cut();
rtb.ReadOnly = readOnly;
}
Trying to keept the formatting alive yourself is a tedious and error-prone waste of your time.
In addition to font properties you would also have to resore all other things you can set with the SelectedXXX properties, like colors, alignment, spacing etc etc..
To delete the first 3 lines use:
DeleteLines(yourRTB, 0, 3);
To restrict the text to 10 lines use:
DeleteLines(yourRTB, 0, yourRTB.Lines.Length - 10);
Note that the function above should have a few checks for valid input; I left them out as the checks somehow need a decision what to do, if count or fromLine if greater than Lines.Length or if fromLine is negative..
While we are at it, here is how to append a bold line:
yourRTB.SelectionStart = yourRTB.Text.Length;
yourRTB.SelectionLength = 0;
using (Font font = new Font(yourRTB.SelectionFont, FontStyle.Bold))
yourRTB.SelectionFont = font;
yourRTB.AppendText(yourNewLine + textOfNewLine);
Of course it really shold go into a reuseable function that the the bolding as a parameter..
Update:
since you are using WordWrap you may prefer this function. It deletes the actual lines, not the visible ones:
void DeleteLinesWW(RichTextBox rtb, int fromLine, int count)
{
int nll = 1; // <<=== pick the length of your new line character(s)!!
int pS = rtb.Lines.Take(fromLine).Select(x => x.Length + nll).Sum() - nll;
int pL = rtb.Lines.Take(fromLine + count).Select(x => x.Length + nll).Sum() - nll;
if (pS < 0) { pS = 0; pL++; }
rtb.SelectionStart = pS;
rtb.SelectionLength = pL - pS ;
bool readOnly = rtb.ReadOnly;
rtb.ReadOnly = false; // allow change even when the RTB is readonly
rtb.Cut();
rtb.ReadOnly = readOnly;
}
A word on NewLine: Do note that I have not used the Environment.NewLine constant as it not really a good idea. If you add multiline text to the RichTextBox in the designer and then look at it you will see that it uses simple '\n' new lines, no returns, no NL-CR, just '\n'. So this seems to be the generic way in a winforms RTB and I recommend using it..
The new function relies on all lines having a newline of the same length!
To make sure you can use this replacement function:
int RTBReplace(RichTextBox rtb, string oldText, string newText)
{
int p = 0; int count = 0;
do
{
p = richTextBox1.Text.IndexOf(oldText);
if (p >= 0)
{
richTextBox1.SelectionStart = p;
richTextBox1.SelectionLength = oldText.Length;
richTextBox1.SelectedText = newText;
count ++;
}
}
while (p >= 0);
return count;
}
Calling it like this:
RTBReplace(yourrichTextBox, "\r\n", "\n");
Update 2:
Here is an example how to add your chat lines:
private void button1_Click(object sender, EventArgs e)
{
string cLine = "Taw: Hello World"; // use your own lines!
var chatstr = cLine.Split(new string[] { ": " }, 2, StringSplitOptions.None);
AppendLineBold(yourrichTextBox, "\n" + chatstr[0], true);
AppendLineBold(yourrichTextBox, chatstr[1], false);
yourrichTextBox.ScrollToCaret();
}
void AppendLineBold(RichTextBox rtb, string text, bool bold)
{
rtb.SelectionStart = richTextBox1.Text.Length;
rtb.SelectionLength = 0;
using (Font font = new Font(rtb.SelectionFont,
bold ? FontStyle.Bold : FontStyle.Regular))
rtb.SelectionFont = font;
rtb.AppendText(text);
}
Update 3:
Looks like the ReadOnly property disallows the use of Cut. So we need to temporatily allow changes.
Funny: SelectedText can't be set either, but AppendText works fine..
To keep text formatting, you can also try the following (it's a little shorter and should also do the trick)
string text = "Username: hello this is a chat message";
// delete the first line when after 10 lines
if (ChatText.Lines.Length >= 10)
{
ChatText.SelectionStart = 0; // set SelectionStart to the beginning of chat text (RichTextBox)
ChatText.SelectionLength = ChatText.Text.IndexOf("\n", 0) + 1; // select the first line
ChatText.SelectedText = ""; // replace by an empty string
ChatText.SelectionStart = ChatText.Text.Length; // set SelectionStart to text end to make SelectionFont work for appended text
}
// split the string in chatstr[0] = username, chatstr[1] = message
string[] chatstr = text.Split(new string[] { ": " }, 2, StringSplitOptions.None);
// make the username bold
ChatText.SelectionFont = new Font(ChatText.Font, FontStyle.Bold);
ChatText.AppendText(chatstr[0] + ": ");
// make the message regular
ChatText.SelectionFont = new Font(ChatText.Font, FontStyle.Regular);
ChatText.AppendText(chatstr[1] + Environment.NewLine);
ChatText.ScrollToCaret();

Delete the last line of rich Text Box?

I like to delete last line of richtextbox which has ended with ; semicolumn. I like to delete this line until ; semicolumn that comes before the last semicolumn.
Example:
hello do not delete this line;
hello this sentence will continue...
untill here;
result should be:
hello do not delete this line;
My Code:
private void button1_Click_1(object sender, EventArgs e) {
List<string> myList = richTextBox1.Lines.ToList();
if (myList.Count > 0) {
myList.RemoveAt(myList.Count - 1);
richTextBox1.Lines = myList.ToArray();
richTextBox1.Refresh();
}
}
Found the solution here:
RichTextBox1.Lines = RichTextBox1.Lines.Take(RichTextBox1.Lines.Length - 3).ToArray();
Use this:
var last = richTextBox1.Text.LastIndexOf(";");
if (last > 0)
{
richTextBox1.Text = richTextBox1.Text.Substring(0, last - 1);
var beforelast = richTextBox1.Text.LastIndexOf(";");
richTextBox1.Text = richTextBox1.Text.Substring(0, beforelast + 1);
}
else
{
richTextBox1.Text = "";
}
You did not specify the other scenarios(i.e, when the string does not contain ";")
this code removes the string starting at ";" just before the last ";" to the last ";".
It removes the last semicolon and texts after that, then finds the new last ";". finally removes the text after this ";"
For those that find this question after all these years...
The solutions that use the .Text property or .Lines property end up removing the formatting from the existing text. Instead use something like this to preserve formatting:
var i = textBox.Text.LastIndexOf("\n");
textBox.SelectionStart = i;
textBox.SelectionLength = o.TextLength - i + 1;
textBox.SelectedText = "";
Note that if your textbox is in ReadOnly mode, you can't modify SelectedText. In that case you need to set and reset ReadOnly like this:
textBox.ReadOnly = false;
textBox.SelectedText = "";
textBox.ReadOnly = true;
I'm not sure exactly how the rich text box works, but something like
input = {rich text box text}
int index = text.lastIndexOf(";");
if (index > 0)
{
input = input.Substring(0, index);
}
// put input back in text box
How about that ?
string input = "your complete string; Containing two sentences";
List<string> sentences = s.Split(';').ToList();
//Delete the last sentence
sentences.Remove(sentences[sentences.Count - 1]);
string result = string.Join(" ", sentences.ToArray());
int totalcharacters = yourrtb.Text.Trim().Length;
int totalLines = yourrtb.Lines.Length;
string lastLine = yourrtb.Lines[totalLines - 1];
int lastlinecharacters = lastLine.Trim().Length;
yourrtb.Text = yourrtb.Text.Substring(0, totalcharacters - lastlinecharacters);

split text in a text file

How can I split a text file where I have various length of sentences inside and I want to read the text file when I click to button1 on my form and take, extract words from that text file that are between start and the end of ' character and which contains # symbol or # symbol inside the start and end of ' character and I want to know which line is it in and output the words into the text file.
Example, lets say I have a text like
abc'123'#def'456''#ghi'
abc'123'#def'#456''#ghi'123456'
output:
1st sentence #ghi
2nd sentence #456 #ghi
PS: #def is not in start and end of ' character so not in the output
I tied with split function but couldn't make it and turned into mass: ( How can I make this. I will be pleased if someone who knows helps.
Thanks.
here ur input string is s & the string contains # or # at first index is str
int start = s.indexOf("'");
int end = s.indexOf("'", start + 1);
string str = s.SubString(start, end);
if(str.ToCharArray()[0] == "#" || str.ToCharArray()[0] == "#")
// proceed
As far as this example is concerned here is a sample code that works
string sen1="abc'123'#def'456''#ghi'";
string sen2 = "abc'123'#def'#456''#ghi'123456'";
string[] NewSen = Regex.Split(sen1, "''");
string YourFirstOP=NewSen[1].ToString(); //gets #ghi
NewSen = Regex.Split(sen2, "''");
string[] A1 = Regex.Split(NewSen[0], "'");
string[] A2 = Regex.Split(NewSen[1], "'");
string YourSecondOP= A1[A1.Length - 1] + "" + A2[A2.Length - 3].ToString();// gets #456 #ghi
But thats just this example
Hope this helps
Try this,
string testString = #"abc'123'#def'456''#ghi'abc'123'#def'#456''#ghi'123456'";
List<string> output = new List<string>();
int startIndex = 0;
int endIndex = 0;
while (startIndex >= 0 && endIndex >= 0)
{
startIndex = testString.IndexOf("'", endIndex + 1);
endIndex = testString.IndexOf("'", startIndex + 1);
if (startIndex >= 0 && endIndex >= 0)
{
string str = testString.Substring(startIndex + 1, (endIndex - startIndex) - 1);
int indexOfSpecialChar = str.IndexOf("#");
if (indexOfSpecialChar < 0)
{
indexOfSpecialChar = str.IndexOf("#");
}
if (indexOfSpecialChar >= 0)
{
output.Add(str.Substring(indexOfSpecialChar));
}
}
}
string [] Mass = s.Split('\'');
if (Mass.Length > 1)
for (int i = 1; i < (Mass.Length - 1); i += 2)
{
if (Mass[i].Contains("#") || Mass[i].Contains("#"))
// proceed
}

Special characters in string.Replace

I want to replace special characters in string.
For example this is input text
http\u00253A\u00252F\u00252Fvideo.l3.fbcdn.net\u00252Fcfs-l3-ash4\u00252F351111\u00252F203\u00252F260478023976707_55781.mp4\u00253Foh\u00253D064626d4996116bdcde2d52f9b70e1f0\u002526oe\u00253D4E566C00\u002526l3s\u00253D20110823082632\u002526l3e\u00253D20110825083632\u002526lh\u00253D0dbcb2d22cd4dd5eb10bf
and then I expect this result :
http://video.l3.fbcdn.net/cfs-l3-ash4/351111...
But string is not replacing as expected
string[] BadCharacters = { "\\u00253A", "\\u00252F", "\\u00253F" };
string[] GoodCharacters = { ":", "/", "?" };
int i;
for (i = 0; i <= 2; i++)
{
textBox2.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}
Your problem is your string gets stomped every iteration through the loop by going back to TextBox1.Text, you need to keep it in a local and keep using the changed value for the next substitution:
var changedText = textBox1.Text;
// always modify and assign to temp, that way we modify previous
for (i = 0; i <= 2; i++)
{
changedText = changedText.Replace(BadCharacters[i], GoodCharacters[i]);
}
textBox2.Text = changedText;
Try this:
var tmp = textBox1.Text;
for (i = 0; i <= 2; i++)
{
tmp = tmp.Replace(BadCharacters[i], GoodCharacters[i]);
}
textBox2.Text = tmp;
textBox2.Text will only ever contain one of the substitutions for each loop, so you likely see only the last iteration.
for (i = 0; i <= 2; i++)
{
textBox1.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}
would likely provide the full substituted string desired.
You need to save the updated value of string each time you replace a substring. So save initial value of textBox1 to textBox2 and use it during iteration. In this way, you won't lose your updated string value.
textBox2.Text = textBox1.Text;
for(i = 0; i <= 2; i++)
{
textBox2.Text = textBox2.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}
Also, by asssigning initial textBox1 value to textBox2 and using it inside your for loop, you save one assigmant statement.

Categories

Resources