简体   繁体   中英

Can not delete the existing file in C#.net

I am trying to upload a file in asp.net. File may be image or pdf. If the file already exist then I have to remove existing file and upload the new file. But if I try to delete existing file, it shows an error that "The process cannot access the file because it is being used by another process" This is the code for my file upload.

if (FileUploadFollowUpUN.HasFile)
{
    if (Request.QueryString.Count > 0 && Request.QueryString["PCD"] != null)
    {
        filename = System.IO.Path.GetFileName(FileUploadFollowUpUN.FileName.Replace(FileUploadFollowUpUN.FileName, Request.QueryString["PCD"] + " " + "D" + Path.GetExtension(FileUploadFollowUpUN.FileName)));
        SaveFilePath = Server.MapPath("~\\ECG\\") + filename;
        DirectoryInfo oDirectoryInfo = new DirectoryInfo(Server.MapPath("~\\ECG\\"));
        if (!oDirectoryInfo.Exists)
            Directory.CreateDirectory(Server.MapPath("~\\ECG\\"));

        if (File.Exists(SaveFilePath))
        {
            File.SetAttributes(SaveFilePath, FileAttributes.Normal);

            File.Delete(SaveFilePath);
        }
        FileUploadFollowUpUN.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
        Session["FileNameFollowUpUN"] = filename;
        if (System.IO.Path.GetExtension(FileUploadFollowUpUN.FileName) == ".pdf")
        {
            imgPhoto.ImageUrl = "~/Images/pdf.jpg";
            ZoomImage.ImageUrl = "~/Images/pdf.jpg";
            imgPhoto.Enabled = true;
        }
        else
        {
            imgPhoto.ImageUrl = "~/ECG/" + filename;
            imgPhoto.Enabled = true;
            ZoomImage.ImageUrl = "~/ECG/" + filename;
        }
    }
}

How can I get rid out of this error?

There is a similar question here on how to find what process is using a file

You should try to dispose any file methods before trying to delete.

You could stick it in a while loop if you have something which will block until the file is accessible

  public static bool IsFileReady(String sFilename)
    {
        // If the file can be opened for exclusive access it means that the file
        // is no longer locked by another process.
        try
        {
            using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                if (inputStream.Length > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }
        catch (Exception)
        {
            return false;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM