How to create file using FileStream.
In this we will create a file using FileStream class and then read it and show the content in a richtextbox.
In this code we will first create a text document. And then we write some text in the textboxes which is saved in the text document that we have created. After that we will read the text entered. We will first read the whole text and then a block of text.
Here I have created the text in the Z drive you can choose your own drive where you want to save.By Editing the below line in the code:
FileStream f = new FileStream("Z:\\new.txt", FileMode.Create, FileAccess.Write);
// We will create a text document in Z drive and write few lines in it.
private void buttonwrite_Click(object sender, EventArgs e)
{
FileStream f = new FileStream("Z:\\new.txt", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(f);
bw.Write(textbxtext.Text);
bw.Close();
f.Close();
MessageBox.Show("File created");
}
This is the code to read text from a file which we have created and saved.
private void buttonread_Click(object sender, EventArgs e)
{
richTextBoxshowdata.Text = "";
FileStream fs = new FileStream("Z:\\new.txt", FileMode.Open, FileAccess.Read);
StreamReader s = new StreamReader(fs);
while (s.Peek() != -1)
{
richTextBoxshowdata.Text += Convert.ToChar(s.Read()).ToString();
}
s.Close();
fs.Close();
}
Now we will read only block of data from the file i.e. suppose we have entered 2-3 lines.From those lines we will read 10 characters only.
private void buttonreadblock_Click(object sender, EventArgs e)
{
richTextBoxshowdata.Text = "";
FileStream fs = new FileStream("Z:\\new.txt", FileMode.Open, FileAccess.Read);
StreamReader s = new StreamReader(fs);
char[] arr = new char[13];
s.ReadBlock(arr, 3, 10);
s.Close();
fs.Close();
for(int i =0;i
richTextBoxshowdata.Text += arr[i].ToString();
}
}