C# StreamReader and StreamWriter for search A word in afile? - c#

Can anybody help me write multiple lines to Text file and then search a specific word in that file. I hope the code will use (File.Exists) if any.... thank you in advance
My Code:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox1.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadLine()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}

thank you all .... I lastly found my Answer I modified the code as below:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox2.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadToEnd()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}

Related

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.

My program is duplicating the input stream from a textbox 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);
}
}

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

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

Show selected text file from one listbox in another

This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
//int LineCount = 0;
while(FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
//LineCount++;
//if(LineCount % 5 == 2)
{
ListBox2.Items.Add(CurrentLine);
}
}
FileRead.Close();
}
but throws exception about:
Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'
When populating the listbox, use the filename instead instead the FileInfo
Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name
protected void Button1_Click(object sender, EventArgs e)
{
ListBox2.Items.Clear();
if (ListBox1.SelectedIndex > -1)
{
string filename = ListBox1.SelectedValue;
StreamReader FileRead = new StreamReader(filename);
string CurrentLine = "";
//int LineCount = 0;
while (FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
ListBox2.Items.Add(CurrentLine);
}
FileRead.Close();
}
else
{
ListBox2.Items.Add("Please select a file first");
}
}
protected void Btn_Load_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\errorlog");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.FullName);
}
}
}

Categories