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

后端 未结 2 1954
再見小時候
再見小時候 2021-01-18 05:09

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         


        
2条回答
  •  无人及你
    2021-01-18 05:39

    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();
    }
    

提交回复
热议问题