public void Persist()
{
var newContents = ToString();
var path = Path.GetDirectoryName(FilePath);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// open the file with exclusive access
using (var fileStream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
// get a current copy of the file
string currentContents = null;
using (var streamReader = new StreamReader(fileStream))
{
currentContents = streamReader.ReadToEnd();
// optimistic concurrency check - make sure the file hasn't changed since it was read
if (string.Equals(currentContents, OriginalContents, StringComparison.Ordinal))
{
// write the new contents
fileStream.Seek(0, SeekOrigin.Begin);
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(newContents);
streamWriter.Flush();
// set the length in case the new contents are shorter than the old contents
fileStream.Flush();
fileStream.SetLength(fileStream.Position);
OriginalContents = newContents;
}
}
else
{
throw new IOException(string.Format(CultureInfo.InvariantCulture,
"Cannot write to file {0}. The file has been modified since it was last read.",
FilePath));
}
}
}
}