Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - FileStream: both lock a file and at the same time be able to read it without truncating it and write it with truncating it

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?

like image 755
pikachu Avatar asked Nov 27 '11 19:11

pikachu


1 Answers

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();
}
like image 122
Oded Avatar answered Sep 22 '22 07:09

Oded