Resources » Code Snippets » File Operations

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


Posted Date: 25-Apr-2008  Last Updated:   Category: File Operations    
Author: Member Level: Silver    Points: 10



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





Did you like this resource? Share it with your friends and show your love!

Responses to "Reading/Writing/Appending a Text File, Using c#"

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

Feedbacks      

Post 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Rajkumar P
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India