Click here to Skip to main content
15,911,762 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've some code:

C#
If(!File.Exists(FILE_ON_NETSHARE))
{
    int val = calc_something();
    try{
        File.WriteAllText(FILE_ON_NETSHARE, "File Created and Calced: " + val);
	created = true;
    }
    cache () {
	// handle
    }
}


First it should check if a file Exists on the Netshare.
If not it should calc a value and and write it to the new created file.

But sometimes the file is created by another process, during calc_something().
But thew file is overwritten, but I want an exception to handl this problem in another way.

But File.WriteAllText(); overwrittes the file without exception.
Posted
Updated 4-Oct-11 16:11pm
v2

You can check if a file exists with File.Exists("filename.ext").

It's not a good idea for everyone to overwrite the contents of a specific file, try appending to the file with some sort of deliminator indicating who added the line etc.

Edited :
C#
if(File.Exists(NETSHARE)==false)
{
   File.WriteAllText(FILE_ON_NETSHARE, "File Created and Calced: " + val);
   created = true;
}
else
{
   // handle
}
 
Share this answer
 
v2
Comments
TomasEe 6-Oct-11 20:28pm    
Know that. ( as you see in example)
But I want to write to a new created File.
If file exists I want an Exception (directly by the try writing ...)
Mehdi Gholam 7-Oct-11 0:17am    
I have edited the solution, you don't need an exception.
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
C#
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:
C#
static void Main()
{
    // this example assumes the share specified here exists and we have the ability to write to it
    string path = @"\\" + Environment.MachineName + @"\Share\Test.txt";

    int val = DoSomeCalculation();
    try
    {
        // assume the file doesn't exist, if it does then an exception will be thrown here
        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)
    {
        // this will be thrown if the file already exists (this includes if another process 
        // using the same code currently has it open). 
        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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900