I suppose my title isn't that clear.
I'll try to explain:
I can write and read a file using a FileStream
FileStream fs = new FileStream("C:\\Users\\Public\\text.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
private void button1_Click(object sender, EventArgs e)
{
fs.Seek(0,0);
StreamReader sr = new StreamReader(fs);
textbox.Text = sr.ReadToEnd();
}
private void button2_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(textbox.Text);
sw.Flush();
}
This way other programs can't use the file, but I also can't delete content. Writing to it only adds the string, it doesn't replace the content.
Or I can do it without a FileStream:
private void button1_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("C:\\Users\\Public\\text.txt");
textBox1.Text = sr.ReadToEnd();
sr.Close();
}
private void button2_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter("C:\\Users\\Public\\text.txt", false);
sw.Write(textBox1.Text);
sw.Close();
}
This way, the content of the file is replaced, but it has no lock on the files.
But I want both. What is the solution?
In your first example, you need to reset the stream before you write to it in order to replace the file contents, instead of appending to it:
private void button2_Click(object sender, EventArgs e)
{
fs.Seek(0,0);
fs.SetLength(Encoding.UTF8.GetBytes(textbox.Text).Length));
StreamWriter sw = new StreamWriter(fs);
sw.Write(textbox.Text);
sw.Flush();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With