System.IO.IOException: the process cannot access the file 'file_name'

I have a method in my windows service as follows:

System.IO.File.Copy(path, ConfigurationManager.AppSettings["BulkInsertGiftRegisterCreatorDirectory"] + System.IO.Path.GetFileName(path));

Loyalty.Entity.Base.FileInfo file = new Loyalty.Entity.Base.FileInfo();
file.FileName = path;
request.Object = file;

ResponseBase response = new ResponseBase(request);
RequestConnection connection = new RequestConnection("cn");
FileManager fileManager = new FileManager(request, connection);
response = fileManager.OfflineGiftRegisterBulkInsert();

System.IO.File.Delete(ConfigurationManager.AppSettings["BulkInsertGiftRegisterCreatorDirectory"] + System.IO.Path.GetFileName(path));

// here is the part of stored procedure that uses file
SELECT @SCRIPT= 'BULK INSERT GIFT_CARD.GIFT_TEMP'
                            +' FROM '''
                            + @FILE_PATH
                            +''' WITH ('
                                 +'FIELDTERMINATOR = '','','
                                 + 'KEEPNULLS'
                            +');'

I can delete the file from the file system manually, but this code tells me "Ooops! System.IO.IOException: the process cannot access the file" filename "because it is being used by another process."

I searched for similar questions on stackoverflow and elsewhere. But I could not find anything to help me. Copy or delete methods return void, and I don't have a thread in my code to post.

How can i fix this?

Thanks in advance.

+3
source share
3 answers

, explorer , . ,

, , , . , .

+4

, :

public static System.Boolean FileInUse(System.String file)
{
    try
    {
        if (!System.IO.File.Exists(file)) // The path might also be invalid.
        {
            return false;
        }

        using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open))
        {
            return false;
        }
    }
    catch
    {
        return true;
    }
}

, , :

public static void WaitForFile(System.String file)
{
    // While the file is in use...
    while (FileInUse(file)) ; // Do nothing.
}

, !

+5

, FileInUse, Vercas:

GC.Collect();
GC.WaitForPendingFinalizers();
+1

Source: https://habr.com/ru/post/1773707/


All Articles