My program is duplicating the input stream from a textbox C# - c#

So, I am a newbie in C# and I have this listbox in my program that is duplicating the contents that it's reading from a textbox.
Whenever I start my program, it loads the contents of the save.txt file to the listbox, but when it does that, it loads a duplicate of all the save.txt content. I tried clearing the listbox before loading the contents but it's not working.
Here's my code:
private void readList()
{
string line;
listBox.Items.Clear(); //I tried to clear the listbox but it's not working
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}
public myAgenda()
{
InitializeComponent();
readList();
}
private void add_btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(add_txt.Text))
{
MessageBox.Show("Error: Please enter a value");
}
else
{
holder = add_txt.Text;
listBox.Items.Add(ctr + " " + holder);
ctr++;
add_txt.Text = " ";
}
}
private void button1_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
Application.Exit();
}

You are filling listbox two time in readlist method i.e.
First Time :
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
Second Time :
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
You can remove either of one approach to fill up the content. First approach is better to use for readability.

You are copying the content twice on your listBox.
Try to do this:
private void readList()
{
string line;
listBox.Items.Clear();
//Comment out this line then put the File Directory on the StreamReader
//listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}

Related

Read text file, split it, then show it in listBox

I need to read a text file containing time stamps and temperatures. The thing is, I need to only show the temperatures in a listBox, spliting the string before displaying it.
So far I've managed to show the text file in the list, but im struggling with removing the timestamps.
My code:
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
string line = "";
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFile.FileName);
while(line != null)
{
line = sr.ReadLine();
if(line != null)
{
string[] newLine = line.Split(' ');
listBox1.Items.Add(newLine);
}
}
sr.Close();
}
}
Now the listBox only shows String[] array.
Oh, and also I need to include this in my code:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
The textfile is in this format:
11:11:11 -10,50
You should take [1] item of the the array after Split:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() != DialogResult.OK)
return;
var temps = File
.ReadLines(openFile.FileName)
.Select(line => line.Split(' ')[1]); // we need temperature only
try {
listBox1.BeginUpdate();
// In case you want to clear previous items
// listBox1.Items.Clear();
foreach (string temp in temps)
listBox1.Items.Add(temp);
}
finally {
listBox1.EndUpdate();
}
}

C# Shorten repeated StreamReader

The following piece of code reads a .txt file and reads a certain line that starts with the characters declared in the code.
private void rb_point1_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point01:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point2_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point02:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point3_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point03:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point4_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point04:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point5_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point05:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
The issue I have is that I have 50 Radio Buttons which means 50 times this code needs repeating. I have no ideas on how to shorten this down or at least make is easier on the eyes
A first improvement would be a method that does what you want and accepts a parameter for the difference. Like so:
private void rb_point1_CheckedChanged(object sender, EventArgs e)
{
ReadLineAndDisplayText("point01:");
}
private void ReadLineAndDisplayText(string lineStart)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith(lineStart))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
Like that you already get rid of most duplication.
Next is to not have a new rb_point1_CheckedChanged() method for each radio button, but assign the same method to all of the buttons. You can then use sender to identify the radio button that was pressed. In the designer, you can e.g. assign the Tag, so your code is like this:
private void anyRadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radio = (RadioButton) sender;
string lineStart = (string) radio.Tag;
ReadLineAndDisplayText(lineStart);
}
Like that you'll end up with only 2 methods.

Read and display in richtext the next line in a text document by clicking a button using C#

I have these list in notepad 1-5 with names
Arman
Betty
Charlie
Delson
Ezra
Situation: when i click the button the name will appear in the richtext one by one until the end of the number. I have this codes yet It's not yet working.
private void button5_Click(object sender, EventArgs e)
{
string file_name = "\\test1.txt";
file_name = textBox1.Text + file_name; //textBox1.Text is my path
int counter = 0;
string line = "";
// Read the file and display it line by line.
StreamReader file = new StreamReader(file_name);
while ((line = file.ReadLine()) != null)
{
richTextBox2.Text = (line);
counter++;
}
file.Close();
// Suspend the screen.
richTextBox2.Text = line; //I use richtext for displaying the output
}
Try this;
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = File.OpenText("yourPath"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
textBox1.Text = line;
this.Refresh();
Thread.Sleep(1000);
}
}
}
Edit 1:
Sorry I made for textbox. Check this;
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = File.OpenText("yourPath"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
richTextBox1.Text += line + "\n";
this.Refresh();
Thread.Sleep(1000);
}
}
}
Since you don't specify if you are writing this application for WPF or WinForms I will assume you are using WPF's RichTextbox. Here is an example:
using (StreamReader sr = new StreamReader("SampleInput.txt"))
{
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
rbResult.Document.Blocks.Add(new Paragraph(new Run(line)));
}
}

Getting extra lines, but I don't know why

I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.

How to use the array of strings and display it line by line

How can I display what has been added to my list and show it in the textbox line by line? I am adding data from a text file into a list so that I can append text after every line.
private void button1_Click(object sender, EventArgs e)
{
try
{
var list = new List<string>();
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
}
TextBox.Text = string.Join(Environment.NewLine, list.ToArray());
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred" + ex.Message);
}
}
Something like:
aTextbox.Text = string.Join(Environment.NewLine, list.ToArray());
This will take every string in your array and add a newline between them.
If you only need to show file source inside a TextBox there is no need to save the data inside a List<string> first. Just do:
string text = "";
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
text += line + Environment.NewLine;
}
}
aTextbox.Text = text;
Another way - without looping through all the lines in the file.
using System.IO;
private void WriteFileContentsToTextBox(string filePath)
{
// Always check for existence of the file
if (File.Exists(filePath))
{
// Open the file to read from.
string[] readText = File.ReadAllLines(filePath, Encoding.UTF8);
myMultilineTextBox.Text = string.Join(Environment.Newline, readText);
}
}

Categories