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 1952
再見小時候
再見小時候 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();
    }
    
    0 讨论(0)
  • 2021-01-18 05:46

    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);
    
    0 讨论(0)
提交回复
热议问题