Divoperat
Divoperat

Reputation: 3

How to manage an error while code try to delete a file that is already in use

I'm quite a beginner in c#, and I hope you could help me. I have to run 8 code in parallel. Seven codes write every 10 second a text file. At the beginning of each minute the files are copied in a different folder. The eighth code reads the files copied every minute at 05 second. My problem is that sometimes the 7 codes can the late in copying the files, and it can happen that it try to delete the files when they are already open by the eighth code, and generate an error System.IO.File.InternalDelete. Can someone let me know how I can handle this error with a code like “On error resume next” I use in VBA.

Thank you in advance for your contributions.

Write_Lines(Output_SERVER);

if ( Directory.Exists(PC_DIRECTORY) && (BarsOfData(1).Status == EBarState.Close || Output_Calcul > Output_Date) )
{
    if (File.Exists(PC_DIRECTORY + @"\" + FILE_NAME)) { File.Delete(PC_DIRECTORY + @"\" + FILE_NAME); }
    File.Copy(SERVER_DIRECTORY + @"\" + FILE_NAME, PC_DIRECTORY + @"\" + FILE_NAME);
}

Upvotes: 0

Views: 80

Answers (1)

Attersson
Attersson

Reputation: 4876

Just try-catch your File.Delete and File.Copy calls and handle this exception:

catch (System.IO.IOException ex)

Therefore:

if ( Directory.Exists(PC_DIRECTORY) && (BarsOfData(1).Status == EBarState.Close || Output_Calcul > Output_Date) )
{
    try 
    {
        if (File.Exists(PC_DIRECTORY + @"\" + FILE_NAME)) 
        { 
            File.Delete(PC_DIRECTORY + @"\" + FILE_NAME);
        }
        File.Copy(SERVER_DIRECTORY + @"\" + FILE_NAME, PC_DIRECTORY + @"\" + FILE_NAME);
    } catch (System.IO.IOException ex) 
    {
        //handle the exception here 
    }
}

Upvotes: 1

Related Questions