It looks like you need to write a placeholder to the shared file while you're doing the calculation so that other processes know that someone else has already claimed it. The method of
if (File.Exists(...))
File.WriteAllText(...)
is an non-atomic operation so there will always be the chance someone writes the file between your checking and writing. I see two possible solutions for you:
(a) instead of just checking for file existence, create the file with nothing in it and use a method that throws if the file already exists. If that succeeds then you can do the calculation and then overwrite the file you created with the results. When other processes try to open/write the file before they do the calculation they'll see the file already exists and exit.
(b) assume the file doesn't exist, do the calculation and then write the file in a way that throws if it already exists.
With Option A you'll have an empty file while you're doing you're calculation, with Option B you run the risk of doing the calculation and then throwing away the result.
Here's Option B:
static void Main()
{
string path = @"\\" + Environment.MachineName + @"\Share\Test.txt";
int val = DoSomeCalculation();
try
{
using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write("File Created and Calced: " + val);
sw.Close();
}
fs.Close();
Console.WriteLine("File created.");
}
}
catch (IOException)
{
Console.WriteLine("File already exists.");
}
Console.WriteLine();
Console.WriteLine("Press ENTER to continue ...");
Console.Read();
return;
}
It demonstrates how to write a file and have it throw if it already exists; modifying this to implement Option A is left as an exercise for the reader. Don't forget to check for other exceptions as well, like UnauthorizedAccess.