I'm trying to replicate Excel's behaviour when opening and editing files, that is:
- File is opened and locked for exclusive write access
- Other users are allowed to read the file
I'm using the following code to open the file, read and prepare for later writing:
_fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
_fileReader = new StreamReader(_fileStream);
_fileWriter = new StreamWriter(_fileStream);
var contents = _fileReader.ReadToEnd();
(In a class that implements IDisposable and disposes the streams)
It apparently works fine aside from one issue when I later save using the following code:
_fileWriter.BaseStream.Seek(0, SeekOrigin.Begin);
_fileWriter.Write(content);
_fileWriter.Flush();
The problem is that I need to truncate the file before saving, and the above only overwrites. If the new content is shorter than what was loaded, I end up with a bad file due to partial old content.
How do I truncate a filestream before writing (but not before reading)?
Is there perhaps a better way to gain exclusive access to the file than what I am doing?