0

I want to delete old image when uploading new one with c# but I get the process cannot access the file because it is being used by another process. error

public void DeleteExistImage(string imageName)
    {
        string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/" + imageName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            stream.Dispose();
            System.IO.File.Delete(path);
        }
    }
  • Move `File.Delete(path)` outside the `using` block. Remove `stream.Dispose()`: that's what the `using` block is for. Assuming the `FileStream` is used to open a stream to send the image. Otherwise, just `File.Delete(path)` after you have closed the Stream that opened the Image. -- I hope you're not trying to create a new Stream to close the original Stream that has been opened somewhere else. – Jimi Jan 27 '21 at 20:09

1 Answers1

0

Try this to delete the file and then create a new file

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

Also, look into the thread if it solves your issue IOException: The process cannot access the file 'file path' because it is being used by another process

Ajinkya Gadgil
  • 117
  • 1
  • 8