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

廉价感情. 提交于 2019-12-01 17:26:12

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 truncate the stream down to 0, it will also work and no need to calculate the new file size in bytes.

fs.Seek(0,0);
fs.SetLength(0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!