Abdulaziz Burghal
Abdulaziz Burghal

Reputation: 866

I can't delete file by .net core 3.1 when the file is opened

I'm trying to delete a file by .net core but the problem while the user opens the file I can't delete it, even if I tried to delete it manually Windows show me this Message:

the action can't be completed because the file is open in IIS worker process

And here is my code :

public async Task deleteFile(long Id)
        {
var UploadedFilesPath = Path.Combine(hosting.WebRootPath, "UploadedFiles");
   
var file = await _repository.GetAsync(Id);

 if (AbpSession.UserId == file.CreatorUserId) {
                try
                {
                    await _repository.DeleteAsync(Id);
                if (File.Exists(file.docUrl))
                {
                        // If file found, delete it   
                        var filePaht = file.docUrl;
                        await Task.Run(() => {
                            File.Delete(filePaht);
                        });

                    }
                }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.InnerException.Message.ToString());
            }
        }
            else
            {
                   
                    throw new UserFriendlyException("Error");
                    
                }
            
        }

Upvotes: 0

Views: 1219

Answers (1)

Useme Alehosaini
Useme Alehosaini

Reputation: 3116

It is very natural/normal that you can not delete, it is (in use). (Even windows OS work like this)

You can wait until it is closed (able to be deleted) and then you delete.

Inside this block:

      if (File.Exists(file.docUrl))
      {
                // If file found, delete it   
                var filePaht = file.docUrl;
                await Task.Run(() => {
                    File.Delete(filePaht);
                });

       }

You should check if it is closed, then delete, like this

      if (File.Exists(file.docUrl))
        {
                FileInfo ff = new FileInfo(file.docUrl)
                if (!ff.IsFileOpen())
                 {
                     var filePaht = file.docUrl;
                     await Task.Run(() => {
                     File.Delete(filePaht);
                     });
                 }

         }

The IsFileOpen extension method can be placed in a static class (for example FileHelpers)

public static class FileHelpers
{
    public static bool IsFileOpen(this FileInfo f)
    {
        FileStream stream = null;

        try
        {
            stream = f.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null) stream.Close();
        }

        return false;
    }
}

Upvotes: 1

Related Questions