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");
}
Thanks it helps me alot.
but what if i want to locate a file manually.
i used a textbox to locate file path.