using System.IO; using System.Text; using System.Threading.Tasks; public static class FileHelper { public static Encoding DefaultEncoding = Encoding.UTF8; public static async Task<byte[]> ReadFileContentAsBytesWithoutLocking(string filePath) { using var inStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var memoryStream = new MemoryStream(); await inStream.CopyToAsync(memoryStream); return memoryStream.ToArray(); } public static async Task<string> ReadFileContentAsStringWithoutLocking(string filePath) { var byteArray = await ReadFileContentAsBytesWithoutLocking(filePath); return DefaultEncoding.GetString(byteArray); } public static void WriteBytesToFileWithoutLocking(string filePath, byte[] content) { using var outStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); outStream.SetLength(0); outStream.Write(content, 0, content.Length); outStream.Flush(); } public static void WriteStringToFileWithoutLocking(string filePath, string content) { WriteBytesToFileWithoutLocking(filePath, DefaultEncoding.GetBytes(content)); } }
819300cookie-checkC# Write files without locking