How to perform different operations on files in c#


In this we will create a text document and perform write and read operation on it. If we click on write button file is created with the data in the textbox. And during read operation it will read the data in the file and display it in the textbox.

In this we will create a text document in C drive.And perform read and write operation on it. First we perform read operation and enter the name and age in Textbox which gets stored in text file. After that we select read button. The name and age is entered in Textbox and message is displayed that binary file readed.


//Write in a text file "binary.txt" and if it doesnot exist it will be created //first and then name and age will be entered.
private void buttonwrite_Click(object sender, EventArgs e)
{
FileStream f = new FileStream("c:\\binary.txt",FileMode.Create,FileAccess.Write);
BinaryWriter b = new BinaryWriter(f);
b.Write(textBoxname.Text);
b.Write(Convert.ToInt32(textBoxage.Text));
b.Close();
f.Close();
MessageBox.Show("File created");
textBoxname.Text = "";
textBoxage.Text = "";
}
//To read a text file "binary.txt" and displays the name and age in textbox.
private void buttonread_Click(object sender, EventArgs e)
{
FileStream f = new FileStream("C:\\binary.txt", FileMode.Open, FileAccess.Read);
BinaryReader rw = new BinaryReader(f);
textBoxname.Text = rw.ReadString();
textBoxage.Text = rw.ReadInt32().ToString();
rw.Close();
f.Close();
MessageBox.Show("Binary file readed");

}


Comments

Author: Aman Gandhi16 Feb 2011 Member Level: Gold   Points : 1

Thanks it helps me alot.

but what if i want to locate a file manually.

i used a textbox to locate file path.

Author: Aman Gandhi16 Feb 2011 Member Level: Gold   Points : 1

there is one problem.it is reading only 3 or 2 lines. what if i want to read complete file.

i want to retire whole text.

Author: sugandha16 Feb 2011 Member Level: Gold   Points : 1

In that case take richtextbox to store value.
And for reading whole text
richtextbox1.Text = rw.ReadToEnd();



  • 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: