How to read textfile line by line into RichTextbox - c#

I have a textfile which contains texts.Now as per my requirement i have to read this textfile line by line into the richtextbox.At present i am reading all lines of the text file at once into richtextbox.Here is my code ..
richTextBox1.Text = File.ReadAllText("E:\\vikas\\abc.txt");
But i want to display the texts of the textfile into richtextbox line by line.

Something like
List<string> lines = File.ReadLines ("E:\\vikas\\abc.txt").ToList();
foreach (string current in lines)
{
richTextBox1.Text += current;
}

not checked, but you just do something like this. you do not want to read it straight into a textbox, because that is slow!!!
using(StreamReader sr = new StreamReader(filename)
{
StringBuilder sb = new StringBuilder();
While(sr.Peek() >-1)
{
sb.Append( sr.ReadLine() );
}
The_Textbox.Text = sb.ToString();
}

Related

How I can copy the text from a TextBox in a textFile?

I created a windows form application and I have a TextBox which has text as a file location like this : C:\DATA\FOLDER.
Also I have a text file in d:\data\test.txtwhich contains many lines but one defined line for Location="" .
How I can copy the location specified in the TextBox in the text file test.txt in the Location="" row, without mentioning the line number ?
You can do it in one line
var path = #"d:\data\test.txt";
File.WriteAllLines(path, File.ReadAllLines(path)
.Select(line => line.StartsWith("Location=\"")
? string.Format("Location=\"{0}\"", textBox1.Text)
: line));
First you read all lines in file and if any of them starts with "Location="" then it will be replaced by the location in text box. At the end you write the result back to the file.
If you don't like to do it in one line (and for me not getting downvoted for it) then you can just split it
var path = #"d:\data\test.txt";
var lines = File.ReadAllLines(path);
var modifiedLines = lines.Select(line =>
{
if (line.StartsWith("Location=\""))
{
return string.Format("Location=\"{0}\"", textBox1.Text);
}
else
{
return line;
}
});
File.WriteAllLines(path, modifiedLines);
I think sometimes writing more code reduces readability!
string text = File.ReadAllText("test.txt");
string filepath=textBox1.Text;
text = text.Replace("Location="" "," Location= "+filepath+");
File.WriteAllText("test.txt", text);
This works too:
IList<string> output = new List<string>();
using (StreamReader sr = new StreamReader("d:\\data\\test.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("Location=\""))
{
line = String.Format("Location=\"{0}\"", "TextBox.Text");
}
output.Add(line);
}
}
File.WriteAllText("d:\\data\\test.txt", string.Join(Environment.NewLine, output));

Read last empty line of a text file

I have funny problem - I tried several scripts that will read text files, and that's ok.
Problem occur when text file have empty line at the end - that line is "ignored".
Code I use is "usual" code for file read, like next one:
string fullFileName;
fullFileName = "myFile.txt";
var lines = File.ReadAllLines(fullFileName);
string fileContent = null;
bool firstLine = true;
foreach (var line in lines) {
if (firstLine != true)
{
//textBox1.Text += System.Environment.NewLine;
fileContent += System.Environment.NewLine;
}
else
{
firstLine = false;
}
//textBox1.Text += line;
fileContent += line;
}
textBox1.Text = fileContent;
So, if last line of file myFile.txt is empty, it is not showed in a TextBox.
Can you help me where is a problem?
I think you could avoid the loop altogether and just do:
textBox1.Text = File.ReadAllText(fullFileName);
This will preserve all the newlines.
It is a problem with the file representation, not with ReadAllLines.
See this thread: http://www.pcreview.co.uk/forums/file-readalllines-doesnt-read-last-blank-line-weird-t3765200.html
Other solution:
using (FileStream fileStream = File.OpenRead("C:\myFile.txt"))
using (StreamReader streamReader = new StreamReader(fileStream))
{
string fileContent = streamReader.ReadToEnd();
textBox1.Text = fileContent;
}
File.ReadAllLines(fullFileName);
does not reads carriage return ('\r'). i think your last line contains only carriage return thats why its not being read. put space in last line to check.
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

StreamWriter replace line with a new text

Is it possible to replace the text in a text file with a new text without erasing the other data, here is my sample code, but its not working, I know there's a problem with it but I can't figure out, thanks,
private void button1_Click_1(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("test10101.txt");
List<string> lines = new List<string>();
while (!sr.EndOfStream)
lines.Add(sr.ReadLine());
output = Convert.ToInt32(textBox1.Text);
newbal = Convert.ToInt32(lines[0]) - output;
MessageBox.Show("Please get your cash....\n\nYour new balance is: $" + newbal);
sr.Close();
{
string linetoreplace = lines[0];
int newlinevalue = newbal;
string contents = sr.ReadToEnd();
StreamWriter sw = new StreamWriter("test10101.txt" + ".tmp");
//contents = Regex.Replace(contents, linetoreplace, newlinevalue.ToString());
contents = contents.Replace(linetoreplace, newlinevalue.ToString());
sw.WriteLine(contents);
sw.Close();
}
I'm wondering if I use the Regex or directly replace the line,
You could do it a lot more easily:
string[] lines = System.IO.File.ReadAllLines("test");
lines[0] = /* replace with whatever you need */
System.IO.File.WriteAllLines("test", lines);
hope this helps
also I'd suggest using int.TryParse if you don't want an exception to be raised in your portion of code in case the first line of the file or the textbox values aren't numeric
if you really want to use the streamwriter you could go with this, also a simpler way:
line[0] = newbal.ToString();
foreach(string s in lines)
sw.WriteLine(s);

C#: Searching for a keyword in a txt file

I have a problem reading a comma-delimited TXT file. This is what I am trying to do. I'm searching a text file for a keyword and then, when I've found the line containing that keyword, getting the whole line of comma-delimited keywords into a string array. How can I do this?
Thanks
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
String line;
String[] array;
while((line = file.ReadLine()) != null)
{
if (line.Contains("myString"))
{
array = line.Split(',');
}
}
file.Close();
In the if part yo can save your comma separated strings to an array
Basically, you're going to want to read the file line by line and check each of those lines for your string. When you find it, you'll take that line and split it into an array.
string temp = "";
string[] list;
IO.FileStream file = new IO.FileStream("MyFile.txt", IO.FileMode.Open);
IO.StreamReader reader = new IO.StreamReader(file);
While (!reader.EndOfStream)
{
temp = reader.ReadLine();
if (temp.Contains("myString")
{
list = temp.split(",");
break;
}
}
reader.close();

Parsing individual lines in a robots.txt file with C#

Working on an application to parse robots.txt. I wrote myself a method that pulled the the file from a webserver, and threw the ouput into a textbox. I would like the output to display a single line of text for every line thats in the file, just as it would appear if you were looking at the robots.txt normally, however the ouput in my textbox is all of the lines of text without carriage returns or line breaks. So I thought I'd be crafty, make a string[] for all the lines, make a foreach loop and all would be well. Alas that did not work, so then I thought I would try System.Enviornment.Newline, still not working. Here's the code as it sounds now....how can I change this so I get all the individual lines of robots.txt as opposed to a bunch of text cobbled together?
public void getRobots()
{
WebClient wClient = new WebClient();
string url = String.Format("http://{0}/robots.txt", urlBox.Text);
try
{
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
string[] lines = new string[] { read.ReadToEnd() };
foreach (string line in lines)
{
textBox1.AppendText(line + System.Environment.NewLine);
}
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK);
}
}
You are reading the entire file into the first element of the lines array:
string[] lines = new string[] {read.ReadToEnd()};
So all your loop is doing is adding the whole contents of the file into the TextBox, followed by a newline character. Replace that line with these:
string content = read.ReadToEnd();
string[] lines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
And see if that works.
Edit: an alternative and perhaps more efficient way, as per Fish's comment below about reading line by line—replace the code within the try block with this:
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
while (read.Peek() >= 0)
{
textBox1.AppendText(read.ReadLine() + System.Environment.NewLine);
}
You need to make the textBox1 multiline. Then I think you can simply go
textBox1.Lines = lines;
but let me check that
Try
public void getRobots()
{
WebClient wClient = new WebClient();
string robotText;
string[] robotLines;
System.Text.StringBuilder robotStringBuilder;
robotText = wClient.DownloadString(String.Format("http://{0}/robots.txt", urlBox.Text));
robotLines = robotText.Split(Environment.NewLine);
robotStringBuilder = New StringBuilder();
foreach (string line in robotLines)
{
robotStringBuilder.Append(line);
robotStringBuilder.Append(Environment.NewLine);
}
textbox1.Text = robotStringBuilder.ToString();
}
Try using .Read() in a while loop instead of .ReadToEnd() - I think you're just getting the entire file as one line in your lines array. Debug and check the count of lines[] to verify this.
Edit: Here's a bit of sample code. Haven't tested it, but I think it should work OK;
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
List<string> lines = new List<string>();
string nextLine = read.ReadLine();
while (nextLine != null)
{
lines.Add(nextLine);
nextLine = read.ReadLine();
}
textBox1.Lines = lines.ToArray();

Categories