gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:00:14 26 4
gpt4 key购买 nike

我想我的标题不是那么清楚。

我会试着解释一下:

我可以使用 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();
}

这样其他程序就不能使用文件了,但是我也不能删除内容。写入它只会添加字符串,不会替换内容。

或者我可以在没有 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();
}

这样,文件的内容被替换了,但是没有对文件加锁。

但我两个都想要。解决方案是什么?

最佳答案

在您的第一个示例中,您需要在写入流之前重置流以替换文件内容,而不是附加到它:

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

关于C#-文件流 : both lock a file and at the same time be able to read it without truncating it and write it with truncating it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com