Reputation: 21
I am trying to write a program to me should be a lot easier than it is proving.
I have a form with text boxes that asks the user to enter their details e.g. Name, Address etc.. What I am trying to achieve is to save the data from the text boxes into a .txt file when the user hits the save button.
I am able to create the file but the data will not save into the file. I have posted my code below, and any help you may have will be greatly appreciated.
private void btnSave_Click(object sender, EventArgs e)
{
string file_name = "e:\\test1.txt";
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name, true);
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
MessageBox.Show("Details have been saved");
}
Upvotes: 1
Views: 26347
Reputation: 94
It would be more practical to use using
at the beginning of the code line where StreamWriter is present. This is to ensure data are Disposed
, you'll need this to unlock the data from the stream.
When writing data:
using (StreamWriter objWriter = new StreamWriter("test1.txt"))
{
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
MessageBox.Show("Details have been saved");
}
When reading saved data, let's use a listbox just to have an example:
foreach (var line in File.ReadAllLines("test1.txt"))
{
listBox1.Items.Add(line);
}
Hope this helps!
Upvotes: 2
Reputation: 14059
It is a good practice to wrap local variables implementing IDisposable
into the using
statement:
using (StreamWriter objWriter = new StreamWriter(file_name, true))
{
objWriter.Write(txtName.Text);
objWriter.Write(txtAddress.Text);
objWriter.Write(txtEmail.Text);
objWriter.Write(txtPhone.Text);
}
This also has a positive side effect: the stream is flushed and closed right after execution of the using
statement.
Suggestion: Consider using WriteLine
instead of Write
, because probably you need a delimiter between string values.
Upvotes: 2
Reputation: 101681
Call StreamWriter.Flush
method after you done:
objWriter.Flush();
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
You could also do this using File.WriteAllText
method:
var line = string.Join(" ", txtName.Text, txtAddress.Text, txtEmail.Text,txtPhone.Text);
File.WriteAllText(file_name, line);
Upvotes: 1