Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Last active March 19, 2020 15:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugberkugurlu/a5a65602e30260eef00b to your computer and use it in GitHub Desktop.
Save tugberkugurlu/a5a65602e30260eef00b to your computer and use it in GitHub Desktop.
C# Atomic File Write Sample
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AtomicWriteSample
{
class Program
{
static void Main(string[] args)
{
string filePath = Path.Combine(Path.GetTempPath(), "foo.txt");
Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, i =>
{
byte[] fileContent = Encoding.UTF8.GetBytes("hello there: " + i.ToString());
using (Stream stream = new MemoryStream(fileContent))
{
try
{
WriteFile(filePath, stream);
Console.WriteLine("Winner: " + i.ToString() + ", ThreadId: " + Thread.CurrentThread.ManagedThreadId);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ": " + i.ToString() + ", ThreadId: " + Thread.CurrentThread.ManagedThreadId);
}
}
});
Console.ReadLine();
}
static void WriteFile(string filePath, Stream fileStream)
{
string tempFilePath = Path.GetTempFileName();
using (FileStream tempFile = File.OpenWrite(tempFilePath))
{
fileStream.CopyTo(tempFile);
}
try
{
File.Move(tempFilePath, filePath);
}
catch (Exception ex)
{
try
{
File.Delete(tempFilePath);
}
catch (Exception)
{
Console.WriteLine("cannot delete as well!!!");
}
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment