如何锁定文件,读取其内容并覆盖它?
HowTo lock a file, read its content and overwrite it?
我需要读取文件的内容并在文件被锁定时覆盖它。我不希望文件在读写操作之间被解锁。
using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
using (var reader = new StreamReader(file, Encoding.Unicode))
using (var writer = new StreamWriter(file, Encoding.Unicode))
{
// read
// calculate new content
// overwrite - how do I do this???
}
}
如果我使用两个 FileStream
s,文件在实例化编写器时被清除,但文件将在 reader 和编写器实例化之间短暂解锁。
using (var reader = new StreamReader(new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)))
{
// read
// calculate new content
}
using (var writer = new StreamWriter(new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)))
{
// write
}
如果你保持打开原来的 FileStream 你可以做到:
using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
// This overload will leave the underlying stream open
using (var reader = new StreamReader(file, Encoding.Unicode, true, 4096, true))
{
//Read
}
file.SetLength(0); //Truncate the file and seek to 0
using (var writer = new StreamWriter(file, Encoding.Unicode))
{
//Write the new data
}
}
我需要读取文件的内容并在文件被锁定时覆盖它。我不希望文件在读写操作之间被解锁。
using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
using (var reader = new StreamReader(file, Encoding.Unicode))
using (var writer = new StreamWriter(file, Encoding.Unicode))
{
// read
// calculate new content
// overwrite - how do I do this???
}
}
如果我使用两个 FileStream
s,文件在实例化编写器时被清除,但文件将在 reader 和编写器实例化之间短暂解锁。
using (var reader = new StreamReader(new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)))
{
// read
// calculate new content
}
using (var writer = new StreamWriter(new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)))
{
// write
}
如果你保持打开原来的 FileStream 你可以做到:
using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
// This overload will leave the underlying stream open
using (var reader = new StreamReader(file, Encoding.Unicode, true, 4096, true))
{
//Read
}
file.SetLength(0); //Truncate the file and seek to 0
using (var writer = new StreamWriter(file, Encoding.Unicode))
{
//Write the new data
}
}