in c# Read full txt file - c#

I tried to do a form application and I have a problem about use StreamReader feature. in StreamWriter feature, I did it but StreamReader just read the last line and The txt file contains, in many rows for example: names and phone numbers but like I said the code read last line
private void button2_Click(object sender, EventArgs e)
{
//1
StreamWriter sw;
sw = File.AppendText("metinbelgesi.txt");
sw.Write(textBox1.Text + " ");
sw.Write(textBox2.Text + " ");
sw.WriteLine(textBox3.Text+"." );
sw.Flush();
sw.Close();
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
FileStream fs = new FileStream("metinbelgesi.txt", FileMode.Open, FileAccess.Read);
StreamReader sw = new StreamReader(fs);
//sw = File.AppendText("metinbelgesi.txt");
string yazi = sw.ReadLine();
while (yazi != null)
{
richTextBox1.Text = yazi;
}
sw.Close();
fs.Close();
}
else
{
MessageBox.Show("First, You Join.");
}
}
What do I do?

You are reading it line by line and keep overwriting richTextBox1 with the next line... try:
richTextBox1.Text = "";
while (yazi != null)
{
richTextBox1.Text += yazi;
yazi = sw.ReadLine();
}
Or, if you don't need to parse each line, you can read it all in one go:
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}

According to your code, you're only reading the first line. There should be a ReadLine() statement inside your loop as well.
Pay attention that you will always overwrite the contents of the textbox with the line of text you've just read.
So, when you've finished your loop, only the last line that you've read will occur in the textbox.
For simplicity, you can also have a look at the File class and more specifically the ReadAllLines() method.

You should probaby try to make your life easier by using some of the simpler File operations.
Try this instead:
private void button2_Click(object sender, EventArgs e)
{
File.AppendAllText("metinbelgesi.txt", $"{textBox1.Text} {textBox2.Text} {textBox3.Text}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
else
{
MessageBox.Show("First, You Join.");
}
}

Related

Create and write into the txt file with one button

I would like to create the txt file that has name from my textbox1 and at the same time, I would like to write in it text from my textbox2.
Can you help me?
I have tried this
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text +
".txt";
File.Create(path);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(textBox1.Text);
}
}
I would suggest you first check if the file already exists, and only create it if not.
Something like:
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text + ".txt";
if (!File.Exists(path))
{
File.Create(path);
}
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}
}
Note : in case you would like your code to append line to the file and not to re-write it, change the secont argument to "true": new StreamWriter(path, true)
Note 2 : You wrote the value of the first text box to the file instead of the second one. hence, in your code the text in the file will be the same as it's name.
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}

Large strings added to a text box freezing my program

This program opens files into a textbox. It works fine with small files such as 4KB in size, but I am having trouble with a 200KB file. Ideally, I want to be able to open files of any size, but opening large files into a text box freezes the program. What am I doing wrong?
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
textBox1.Text = String.Empty;
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + Environment.NewLine;
}
sr.Close();
}
openFileDialog1.Dispose();
}
Reading file line-by-line gives unwanted overhead. It would be better to read all file at once.
Consider to use async/await. This will bring you more responsive interface.
So I would suggest the next solution:
private async void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
textBox1.Text = await sr.ReadToEndAsync();
sr.Close();
}
openFileDialog1.Dispose();
}
Edit
As discussed in the comments, this solution doesn't correctly process unix-style line breaks. For this case it can be other decision:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
var sb = new StringBuilder();
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine());
}
textBox1.Text = sb.ToString();
sr.Close();
}
openFileDialog1.Dispose();
}
Now we are using StringBuilder, which is designed for fast processing of string data.

Cannot convert BinaryReader.PeekChar or ReadChar to String C#

Whenever I try to convert BinaryReader PeekChar or ReadChar to string it gives me an error
Error 1 'System.IO.BinaryReader.PeekChar()' is a 'method', which is
not valid in the given context
How do I convert it? Here is my code sample:
private void openTextToolStripMenuItem_Click(object sender, EventArgs e)
{
myPath = textBox3.Text;
BinaryReader objBinReader = new BinaryReader(File.Open(myPath, FileMode.Open));
listBox1.Hide();
richTextBox1.Show();
richTextBox1.Text = "";
do
{
try
{
richTextBox1.Text = richTextBox1.Text + objBinReader.ReadChar.toString();
}
catch
{
MessageBox.Show(objBinReader.PeekChar.toString());
}
} while (objBinReader.PeekChar.toString() != "-1");
objBinReader.Close();
}
Thanks in advance!
You are missing the () for the method calls
richTextBox1.Text = richTextBox1.Text + objBinReader.ReadChar().ToString();
and
objBinReader.PeekChar().ToString()
In fact, you're reading the file char after char. Why not do it in one (easy) go?
private void openTextToolStripMenuItem_Click(object sender, EventArgs e)
{
listBox1.Hide();
richTextBox1.Text = File.ReadAllText(textBox3.Text);
richTextBox1.Show();
}
An alternative solution with BinaryReader will be
private void openTextToolStripMenuItem_Click(object sender, EventArgs e)
{
listBox1.Hide();
// when building string in a loop use StringBuilder
StringBuilder sb = new StringBuilder();
// do not close BinaryReader manually, put using instead
using (BinaryReader objBinReader = new BinaryReader(File.OpenRead(textBox3.Text)))
{
// PeekChar() is a method, notice ()
while (objBinReader.PeekChar() != -1)
sb.Append(objBinReader.ReadChar()); // ReadChar() is a method as well
}
richTextBox1.Text = sb.ToString();
richTextBox1.Show();
}

How can I save a list to a file then read the items back into a ListBox?

I am attempting to save a simple list to a file without using Serialize. Is this possible?
public partial class Form1 : Form
{
public List<string> _testList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int _add = 0;
string _addString ="";
for (int i = 0; i < 5; i++)
{
_add =+ i;
_addString = Convert.ToString(_add);
_testList.Add(_addString);
}
TextWriter tw = new StreamWriter("SavedList.txt", true);
foreach (string s in _testList)
tw.WriteLine(s);
tw.Close();
StreamReader streamReader = new StreamReader("SavedList.txt");
// Read the data to the end of the stream.
listBox1.Text = streamReader.ReadToEnd();
// Close the text stream reader.
streamReader.Close();
// Close the file stream.
//fileStream.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
This emits no errors, however it does nothing.
I will use Serialize if necessary, however the suspicion is that is not necessary. Is it?
You can use the File Class to facilitate this.
File.WriteAllLines("SavedList.txt", _testList.ToArray());
To read it back you can then use:
string[] lines = File.ReadAllLines("SavedList.txt");
foreach (string line in lines)
listBox1.Items.Add(line);
your problem is that the Text field of ListBox
doesn't work like that.
change:
listBox1.Text = streamReader.ReadToEnd();
to:
foreach(string s in streamReader.ReadToEnd().Split(new string[]{"\r\n"}))//!!!the end of line characters may differ depending on your system!!!
{
listBox1.Items.Add(s);
}
the Text field holds the currently selected text . it is not for adding items to the list.

Read from a text file and write it to another text file into a comma delimited format using StreamWriter

I am trying to write data that has been read from a text file and write it to another text file into a comma delimited format. I need to know what the code is to come to that conclusion. This where I need the help.
Example:
Original Data looks like this:
Agnico-Eagle Mines
COM
008474108
28996843
716800
716800
N/A
N/A
N/A
716800
N/A
Agrium Inc.
COM
008916108
145739616
1646617
1646617
N/A
N/A
N/A
1646617
N/A
AuRico Gold Inc
COM
05155C105
504505
62875
62875
N/A
N/A
N/A
62875
N/A
This is how I want the data to look like in the RichTextBox:
Agnico-Eagle Mines,COM,008474108,28996843,716800,716800,N/A,N/A,,N/A,716800,N/A
Agrium Inc.,COM,008916108,145739616,1646617,1646617,N/A,N/A,,N/A,1646617,N/A
AuRico Gold Inc,COM,05155C105,504505,62875,62875,N/A,N/A,,N/A,62875,N/A
Just so you know from the original text data, I want to read the first line, then add a comma and then read the 2nd line append it to the first line then add a comma, and this goes one for the 1st 12 lines. The end of the 12th line has no comma. Then the process starts over again.
Any info is appreciated.
Thanks.
Below is the code that I have written thus far.
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader Reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
while (!Reader.EndOfStream)
{
TextBox1.AppendText(Reader.ReadLine());
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter Writer = new StreamWriter(#"C:\Original_Text_File.txt"))
{
Writer.WriteLine(TextBox1.Text);
}
}
This is the way that I would approach reading the data:
var sbText = new System.Text.StringBuilder(10000);
// Keeps track of your current position within a record
int wCurrLine = 0;
// Number of rows in the file that constitute a record
const int LINES_PER_ROW = 12;
using (StreamReader Reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
while (!Reader.EndOfStream)
{
// If we are not on the first row in the record, add a comma
if (wCurrLine != 0)
{
sbText.Append(",");
}
// Add the text
sbText.Append(Reader.ReadLine());
// Increment our current record row counter
wCurrLine++;
// If we have read all of the rows for this record
if (wCurrLine == LINES_PER_ROW)
{
// Add a line to our buffer
sbText.AppendLine();
// And reset our record row count
wCurrLine = 0;
}
}
// When all of the data has been loaded, write it to the text box in one fell swoop
TextBox1.Text = sbText.ToString();
EDIT: I just realized I didn't answer the original question fully: there is no reason to use the textbox unless you want to see the results before writing them out. If you don't need to do this, you can replace the line:
TextBox1.Text = sbText.ToString();
with:
using (StreamWriter Writer = new StreamWriter(#"C:\Original_Text_File.csv"))
{
Writer.Write(sbText);
}
(Note the change of extension in the file name).
Assuming 12 is the magic number for your input text,
var query = File.ReadLines("a.txt")
.Select((line,no) => new{line,no})
.GroupBy(x => x.no/12)
.Select(g => String.Join(",",g.Select(x => x.line)));
File.WriteAllLines("b.txt",query);
This works for your sample input and expected output....
If you just want to write from one file to another one with differecnt method, try something like this:
protected string TextProperty { get; set; }
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
// read all content file to the string property on your form.
TextProperty = reader.ReadToEnd();
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter(#"C:\Original_Text_File.txt"))
{
// write all content of the property to the file.
writer.Write(TextProperty);
}
}
if you want to separate line by line or do a specifict reatment for each line, you could use StringBuilder class.
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
StringBuilder builder = new StringBuilder();
while (reader.Peek() >= 0)
{
builder.AppendLine(reader.ReadLine());
}
}
}
and to get all the entire content of the StringBuilder just call the ToString() method and write it on the file:
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter(#"C:\Original_Text_File.txt"))
{
writer.Write(builder.ToString());
}
}
NB - I'm leaving this as an example of how to do this if there was a marker (blank line), I miss read the example data when I wrote it.
Something like this should work, I did not test so it might have typos:
Note: I look for a blank line (instead of counting) to know I'm at the end of a record. In this way if you add another field the code won't break.
using (StreamReader Reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
StringBuilder aLine;
boolean first = true;
while (!Reader.EndOfStream)
{
// read source line
string inLine = Reader.ReadLine();
// if length is zero append to test box (we have a blank line between records)
if (inLine.Length == 0)
{
TextBox1.AppendText(aLine.ToString());
first = true;
}
// add a comma if we are not the first
if (!first)
{
aLine.Append(",");
}
aLine.Append(inLine);
// next time we won't be first
first = false;
}
TextBox1.AppendText(aLine.ToString());
}
create a List<String>, read each line into it.. then String.Join the List using a , as a separator. Of course call the Clear method on the list at the beginning of each line.
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader Reader = new StreamReader(#"C:\Original_Text_File.txt"))
{
var i = 0;
while (!Reader.EndOfStream)
{
if (i % 12 == 11)
{
//every 12 lines you read append new line instead of ,
TextBox1.AppendText(string.Format("{0}\n", Reader.ReadLine()));
}
else
{
TextBox1.AppendText(string.Format("{0},", Reader.ReadLine()));
}
i++;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter Writer = new StreamWriter(#"C:\Original_Text_File.txt"))
{
using (StringReader Reader = new StringReader(TextBox1.Text))
{
while (true)
{
var line = Reader.Readline()
if(line !=null)
{
Writer.WriteLine(Reader.Readline());
}
else
{
break;
}
}
}
}
}

Categories