Reading/Writing/Appending a Text File, Using c#

The following code can be used to read/write/append contents of/to a Text file.

The path and filename can be read from textbox controls in the form.



private void file_write()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;

FileInfo file1=new FileInfo(fname);

StreamWriter sw=file1.CreateText();
sw.WriteLine("This is a demo for writing to a text file"); // Writing a string directly to the file
sw.WriteLine(TextBox2.Text); // Writing content read from the textbox in the form
sw.Close();
}

private void file_read()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;
string readcontent;

FileInfo file1=new FileInfo(fname);

StreamReader sr=new StreamReader(file1);
readcontent=sr.ReadToEnd(); // Reading content from the file and storing to a string
sr.Close();
TextBox2.Text=readcontent; // Display contents in a textbox in the form
}

private void file_append()
{
string path="D:\\Temp\\My Documents\\"; // Parent Directory
string name=TextBox1.Text;
string ext=".txt";
string fname=path+name+ext;
FileInfo file1=new FileInfo(fname);
StreamWriter sw=File.AppendText(file1)
sw.WriteLine("This is a demo for appending text content to a file");
// Writing a string directly to the file
sw.WriteLine(TextBox2.Text); // Writing content read from the textbox in the form
sw.Close();
}




Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: