/// <summary> /// Run a write action to a file. /// This will always rewrite the file (no appending). /// </summary> /// <param name="path">File path to write</param> /// <param name="action">Action to write into file stream. You do not need to close the stream yourself.</param> public static void Write(string path, Action <Stream> action) { lock (_lock) { // if the old copy file exists, this means that we have // a previous corrupt write, so we will not overrite it, but // rather overwrite the current file and keep it as our backup. if (File.Exists(path + ".old_copy") == false) { File.Move(path, path + ".old_copy"); } using ( var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 0x10000, FileOptions.WriteThrough | FileOptions.SequentialScan) ) { SetPermissions.TryAllowReadWriteForAll(path); action(stream); stream.Flush(); } WaitDelete(path + ".old_copy"); } }
/// <summary> /// Run a read action over a file by name. /// Access is optimised for sequential scanning. /// No file share is permitted. /// </summary> /// <param name="path">File path to read</param> /// <param name="action">Action to consume file stream. You do not need to close the stream yourself.</param> public static void Read(string path, Action <Stream> action) { lock (_lock) { if (File.Exists(path + ".old_copy")) { if (WaitDelete(path)) { File.Move(path + ".old_copy", path); } } using ( var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 0x10000, FileOptions.SequentialScan) ) { SetPermissions.TryAllowReadWriteForAll(path); action(stream); } } }
private FileStream CreateWriter() { var dataFilePath = GetDataPath(CurrentFileNumber); var stream = new FileStream( dataFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite, 0x10000, FileOptions.Asynchronous | FileOptions.SequentialScan | FileOptions.WriteThrough); SetPermissions.TryAllowReadWriteForAll(dataFilePath); return(stream); }
void CreateDirectory(string s) { Directory.CreateDirectory(s); SetPermissions.TryAllowReadWriteForAll(s); }