question

AmitMaheshwari-7885 avatar image
0 Votes"
AmitMaheshwari-7885 asked AmitMaheshwari-7885 commented

Some times File.Delete isn't working for temp location

I have below code which I run for several iterations in different times of the day.
Most of the times, it runs as expected but some times it has some issues.

Please find the code below,

                 try
                 {
                     string filePath = Path.GetTempFileName(); //this creates a 0 kb temp file.
    
                     if (File.Exists(filePath))
                         File.Delete(filePath); //it goes here means file exists and no error is being thrown.
                     else
                         Console.WriteLine("File:" + filePath + " didn't get created");
                                 
                     if (File.Exists(filePath))
                         Console.WriteLine("file still exist:" + filePath); //even though no errors, it still find the file
                 }
                 catch(Exception ex)
                 {
                     Console.WriteLine("Error Occured: " + ex.ToString()); //It doesn't go here.
                 }

Here I cannot understand, if the code is able to detect that file exists and try to delete it. It cannot delete the file and No exception is being thrown too.

Am I missing anything?

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
1 Vote"
Viorel-1 answered AmitMaheshwari-7885 commented

If you repeat File.Exists in a loop or after a short delay, you will probably see that the file does not exist. According to some Operation System details, File.Delete marks the file for deletion. Maybe you occasionally observe some transient state of the file if you call File.Exists immediately after File.Delete.

By the way, File.Delete can be called even if file does not exist.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks, I'll try adding the delay before checking if file still exists or not. This was helpful.

0 Votes 0 ·