Cannot convert BinaryReader.PeekChar or ReadChar to String C# - 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();
}

Related

in c# Read full txt file

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

C# textfile only contains last string written to file with StreamWriter

I'm writing a Chat Program in C# (Windows Forms Application), the solution contains to projects which both consist of one form ( see picture ). While sending messages to each other works, I'm trying to record the conversation session in a .txt file named dateTime.txt using StreamWriter. Creating the file if it does not exist yet works, but whenever I open the text file, it only contains the last string that was written to it instead of containing the whole "conversation".
Does anybody know how to fix this?
This is the code of one of the forms, but since the forms do exactly the same, the code is the same too so i'm only posting the code of one Form. Would be great if somebody knows what I have to change so the whole conversation is recorded in the text file.
namespace Assignment3Client
{
public partial class Chat : Form
{
NamedPipeClientStream clientPipe = new NamedPipeClientStream("pipe2");
NamedPipeServerStream serverPipe = new NamedPipeServerStream("pipe1");
string msg = String.Empty;
string msgStr;
string name;
byte[] ClientByte;
public Chat()
{
InitializeComponent();
}
private void btnStartChat_Click(object sender, EventArgs e)
{
this.Text = "Waiting for a connection....";
if (txtBoxName.Text.Length == 0)
{
MessageBox.Show("please enter a name first.");
}
else
{
name = txtBoxName.Text;
clientPipe.Connect();
serverPipe.WaitForConnection();
if (serverPipe.IsConnected)
{
this.Text = "You are connected, " + name + "!";
btnStartChat.Enabled = false;
btnSend.Enabled = true;
txtBoxMsg.Enabled = true;
txtBoxMsg.Focus();
receiveWorker.RunWorkerAsync();
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
msg = "[" + name + ": " + DateTime.Now + "] " + txtBoxMsg.Text;
txtBoxChat.AppendText(msg + "\n");
FileWriter(msg);
sendWorker.RunWorkerAsync(msg); //start backgroundworker and parse msg string to the dowork method
txtBoxMsg.Clear();
txtBoxMsg.Focus();
}
private void sendWorker_DoWork(object sender, DoWorkEventArgs e)
{
Byte[] msgByte = System.Text.Encoding.GetEncoding("windows-1256").GetBytes(msg);
serverPipe.Write(msgByte, 0, msg.Length);
}
private void receiveWorker_DoWork(object sender, DoWorkEventArgs e)
{
ClientByte = new Byte[1000];
int i;
for (i = 0; i < ClientByte.Length; i++)
{
ClientByte[i] = 0x20;
}
clientPipe.Read(ClientByte, 0, ClientByte.Length);
msgStr = System.Text.Encoding.GetEncoding("windows-1256").GetString(ClientByte);
receiveWorker.ReportProgress(i, msgStr);
}
private void receiveWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if ((string)e.UserState == String.Empty)
{ MessageBox.Show("no message"); }
else
{
string message = (string)e.UserState;
txtBoxChat.AppendText(message);
FileWriter(message);
txtBoxChat.BackColor = System.Drawing.Color.DarkBlue;
txtBoxChat.ForeColor = System.Drawing.Color.White;
}
}
private void receiveWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (clientPipe.IsConnected)
{
receiveWorker.RunWorkerAsync();
}
else
{
txtBoxMsg.Enabled = false;
btnSend.Enabled = false;
MessageBox.Show("Connection lost");
}
}
private void Chat_Activated(object sender, EventArgs e)
{
txtBoxChat.BackColor = new System.Drawing.Color();
txtBoxChat.ForeColor = new System.Drawing.Color();
}
private void exitMenuStrip_Click(object sender, EventArgs e)
{
this.Close();
}
private void conMenuSrip_Click(object sender, EventArgs e)
{
}
private void errMenuStrip_Click(object sender, EventArgs e)
{
}
public void FileWriter(string message)
{
string path = #"C:\Users\selin\Documents\TAFE\Term 3\dateTime.txt";
FileStream conLog;
if (!File.Exists(path))
{
conLog = new FileStream(path, FileMode.Create);
}
else
{
conLog = new FileStream(path, FileMode.Open);
}
StreamWriter writer = new StreamWriter(conLog);
writer.WriteLine(message);
writer.AutoFlush = true;
writer.Close();
MessageBox.Show("written to file" + message);
}
}
}
in FileWriter(string message) change
conLog = new FileStream(path, FileMode.Open);
to
conLog = new FileStream(path, FileMode.Append);

.Reading and writing to a file from the same textbox

I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable

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

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

No overload for 'method' matches delegate 'delegate'

This is just a part of the code
A few lines down I'm trying to convert an Int to double. But the fact that the double is an array makes it hard...
I need to include "i" like I did in the previous function, but it wont work, and I get the following error;
No overload for 'webKoordx_OpenReadComplete' matches delegate 'System.Net.OpenReadCompletedEventHandler'
If you know any solution, or is able to see something I've missed, please help me!
private void getKoord(int i)
{
string stringKoX = "http://media.vgy.se/kristoferpk/spots/" + i + "/koordinatx.html";
string stringKoY = "http://media.vgy.se/kristoferpk/spots/" + i + "/koordinaty.html";
var webKoordx = new WebClient();
webKoordx.OpenReadAsync(new Uri(stringKoX));
webKoordx.OpenReadCompleted += new OpenReadCompletedEventHandler(webKoordx_OpenReadComplete);
var webKoordy = new WebClient();
webKoordy.OpenReadAsync(new Uri(stringKoY));
webKoordy.OpenReadCompleted += new OpenReadCompletedEventHandler(webKoordy_OpenReadComplete);
}
void webKoordx_OpenReadComplete(object sender, OpenReadCompletedEventArgs e, int i)//<<-----
{
try
{
using (var reader = new StreamReader(e.Result))
{
koordx = reader.ReadToEnd();
koordx_d[i] = Convert.ToDouble(koordx);
}
}
catch
{
MessageBox.Show("Kan ej ansluta");
MessageBox.Show("Kontrollera din anslutning");
}
}
void webKoordy_OpenReadComplete(object sender, OpenReadCompletedEventArgs e)//<<-----
{
try
{
using (var reader = new StreamReader(e.Result))
{
koordy = reader.ReadToEnd();
koordy_d[i] = Convert.ToDouble(koordy);
}
}
catch
{
MessageBox.Show("Kan ej ansluta");
MessageBox.Show("Kontrollera din anslutning");
}
}
You cannot pass extra information to an event handler like that.
Instead, you can add a lambda expression that handles the event and passes your extra information from its closure:
webKoordx.OpenReadCompleted += (sender, e) => MyMethod(e.Result, i);

Categories