Web应用程序无法删除ASP.NET中启用读/写功能的文件夹的文件

Web应用程序无法删除ASP.NET中启用读/写功能的文件夹的文件,asp.net,file-io,ftp,shared-hosting,Asp.net,File Io,Ftp,Shared Hosting,当我试图删除我通过名为“SampleApplication”的网站上传的图像时,我可以看到堆栈跟踪中显示的以下错误 The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process. Description: An unhandled exception occurred during

当我试图删除我通过名为“SampleApplication”的网站上传的图像时,我可以看到堆栈跟踪中显示的以下错误

 The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.]
   System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +9723350
   System.IO.File.Delete(String path) +9545728
   SampleApplication.BasePage.DeleteApp_ImagesById(DataTable dt) +503
   SampleApplication.PostLease.MyAccount.DeleteAd_Property(Object sender, EventArgs e) +193
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 
文件夹App_映像已被授予读/写权限,并继承到子文件夹,即myfolder1、myfolder2、myfolder3、myfolder4。即使我试图从FTP文件管理器中强制删除图像eKuK2511.png,它仍显示以下错误:

550 The process cannot access the file because it is being used by another process. 
如何消除这个错误

编辑: 上传代码:

public void UploadImages()
        {
            if (ServerSideValidation() == true)
            {
                string SavePath;
                ImgPaths = new List<string>();
                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                if (hfc.Count > 0)
                {
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            #region trials compression.
                            SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + GetUniqueKey() + GetFileExtension(hpf.FileName);
                            SaveImageByCompressing(hpf, SavePath);

                            #endregion
                            //SavePath can be saved in DB.
                            ImgPaths.Add(SavePath);
                            //Save Thumbnail Image.
                            if (i == 0)
                            {
                                string savedName = "Thumb_" + GetUniqueKey() + GetFileExtension(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "\\").Replace("/", "\\"));
                                SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + savedName;
                                SaveThumbImage(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "").Replace("/", "\\"), AppDomain.CurrentDomain.BaseDirectory + "App_Images\\" + Session["AppContext"].ToString() + "\\" + savedName, 75, 75);
                                ImgPaths.Add(SavePath);
                            }
                        }
                    }
                    Session.Remove("AppContext");
                    lblMsg.Text = "Images Uploaded Successfully.";
                    //ShowUploadedImages(ImgPaths);
                }
                else
                {
                    lblMsg.Text = "Images uploaded are either in wrong format or were deleted after uploading.";
                }
            }
            else
            {
                lstPaths = new List<string>();
                lblMsg.Text = "No Images Uploaded";
            }
        }

        private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
        {
            Image imgFromClient = Image.FromStream(hpf.InputStream);
            string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("~/", "").Replace("/", "\\");
            Image.GetThumbnailImageAbort myCallbackCompressed = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width, imgFromClient.Height, myCallbackCompressed, IntPtr.Zero);
            imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);

        }
        public static void SaveThumbImage(string imagePath, string filePath, int width = 0, int height = 0)
        {
            Image originalImage = Image.FromFile(imagePath);
            if (width > 0 && height > 0)
            {
                Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                Image imageToSave = originalImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
                imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
        private static bool ThumbnailCallback() { return false; }

        private bool ServerSideValidation()
        {
            string errorMsg = string.Empty, temp = null;
            bool errorFlag = true;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0 && hpf.FileName!=String.Empty)
                {
                    temp = ValidateImage(hpf);
                    if (temp != null)
                    {
                        errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                        temp = null;
                    }
                }
                else
                {
                    return false;
                }
            }

            if (!string.IsNullOrWhiteSpace(errorMsg))
            {
                lblMsg.Text = errorMsg;
                errorFlag = false;
            }
            return errorFlag;
        }

        private string GetFileExtension(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            return fi.Extension;
        }

        private string GetFileName(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            return fi.Name;
        }

        private string GetUniqueKey()
        {
            int maxSize = 8;
            char[] chars = new char[62];
            string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

            chars = a.ToCharArray();

            int size = maxSize;
            byte[] data = new byte[1];

            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

            crypto.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(size);

            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
            return Session["AppContext"].ToString() + Page.User.Identity.Name.ToString() + result.ToString();
        }

        private string ValidateImage(HttpPostedFile myFile)
        {
            string msg = null;
            //6MB
            int FileMaxSize = 6291456;
            //Check Length of File is Valid or Not.
            if (myFile.ContentLength > FileMaxSize)
            {
                msg = msg + "File Size is Too Large. You are allowed only a maximum of 6MB per Image.";
            }
            //Check File Type is Valid or Not.
            if (!IsValidFile(myFile.FileName))
            {
                msg = msg + "Invalid File Type.";
            }
            return msg;
        }

        private bool IsValidFile(string filePath)
        {
            bool isValid = false;

            string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

            for (int i = 0; i < fileExtensions.Length; i++)
            {
                if (filePath.ToUpper().Contains(fileExtensions[i]))
                {
                    isValid = true; break;
                }
            }
            return isValid;
        }
public void UploadImages()
{
if(ServerSideValidation()==true)
{
字符串保存路径;
ImgPaths=新列表();
//获取HttpFileCollection
HttpFileCollection hfc=Request.Files;
如果(hfc.Count>0)
{
对于(int i=0;i0)
{
#区域试验压缩。
SavePath=“~/App\u Images/”+会话[“AppContext”].ToString()+“/”+GetUniqueKey()+GetFileExtension(hpf.FileName);
通过压缩保存图像(hpf,保存路径);
#端区
//保存路径可以保存在数据库中。
ImgPaths.Add(保存路径);
//保存缩略图图像。
如果(i==0)
{
string savedName=“Thumb\”+GetUniqueKey()+GetFileExtension(AppDomain.CurrentDomain.BaseDirectory+ImgPaths[0].ToString().Replace(“~/”,“\\”).Replace(“/”,“\\”);
SavePath=“~/App_Images/”+会话[“AppContext”]。ToString()+“/”+savedName;
SaveThumbImage(AppDomain.CurrentDomain.BaseDirectory+ImgPaths[0].ToString().Replace(“~/”,”).Replace(“/”,“\\”),AppDomain.CurrentDomain.BaseDirectory+“App\U Images\\”+会话[“AppContext”]。ToString()+“\\”+savedName,75,75);
ImgPaths.Add(保存路径);
}
}
}
会话。删除(“AppContext”);
lblMsg.Text=“已成功上载图像。”;
//显示上传的图像(ImgPaths);
}
其他的
{
lblMsg.Text=“上载的图像格式错误,或者在上载后被删除。”;
}
}
其他的
{
lstPaths=新列表();
lblMsg.Text=“没有上传图像”;
}
}
私有void SaveImageByCompressing(HttpPostedFile hpf,字符串文件路径)
{
Image imgFromClient=Image.FromStream(hpf.InputStream);
字符串SavetoFullPath=AppDomain.CurrentDomain.BaseDirectory+filePath.Replace(“~/”,“”)。Replace(“/”,“\\”);
Image.GetThumbnailImageAbort myCallbackCompressed=新图像.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave=imgFromClient.GetThumbnailImage(imgFromClient.Width,imgFromClient.Height,myCallbackCompressed,IntPtr.Zero);
imageToSave.Save(SavetoFullPath、System.Drawing.Imaging.ImageFormat.Jpeg);
}
公共静态void SaveThumbImage(字符串imagePath、字符串filePath、int-width=0、int-height=0)
{
Image originalImage=Image.FromFile(imagePath);
如果(宽度>0和高度>0)
{
Image.GetThumbnailImageAbort myCallback=新图像.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave=originalImage.GetThumbnailImage(宽度、高度、myCallback、IntPtr.Zero);
imageToSave.Save(文件路径,System.Drawing.Imaging.ImageFormat.Jpeg);
}
其他的
{
保存(文件路径、系统、绘图、成像、图像格式、Jpeg);
}
}
私有静态bool ThumbnailCallback(){return false;}
私有bool ServerSideValidation()
{
string errorMsg=string.Empty,temp=null;
bool errorFlag=true;
//获取HttpFileCollection
HttpFileCollection hfc=Request.Files;
对于(int i=0;i0&&hpf.FileName!=String.Empty)
{
温度=有效年龄(hpf);
如果(温度!=null)
{
errorMsg+=GetFileName(hpf.FileName.ToString())+“有错误:”+temp;
温度=零;
}
}
其他的
{
返回false;
}
}
如果(!string.IsNullOrWhiteSpace(errorMsg))
{
lblMsg.Text=errorMsg;
errorFlag=false;
}
返回错误标志;
}
私有字符串GetFileExtension(字符串文件路径)
{
FileInfo fi=新的FileInfo(filePath);
返回fi.扩展;
}
私有字符串GetFileName(字符串文件路径)
{
FileInfo fi=新的FileInfo(filePath);
返回fi.Name;
}
私有字符串GetUniqueKey()
{
int maxSize=8;
char[]chars=新字符[62];
字符串a=“ABCDEFGHIJKLMNOPQRSTUVXYZABCDFGHIJKLMNOPQRSTUVXYZ1234567890”;
chars=a.ToCharArray();
int size=maxSize;
字节[]数据=新字节[1];
RNGCryptoServiceProvider crypto=新的RNGCryptoServiceProvider
/// <summary>
        /// Delete all images. If there are no Images then by default NoImage.png is assigned. So skip deleting that image.
        /// </summary>
        /// <param name="dt"></param>
        protected void DeleteApp_ImagesById(DataTable dt)
        {
            if (dt.Rows[0][0].ToString() != "~/images/NoImage.png")
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Rows[0][i].ToString() != string.Empty)
                    {
                        string str = Regex.Replace(dt.Rows[0][i].ToString(), "~/", "");
                        File.Delete(Request.PhysicalApplicationPath.ToString() + Regex.Replace(str, "/", "\\").ToString());
                    }
                }
            }
        }
    private void SaveImageByCompressing(HttpPostedFile hpf, string filePath) 
    { 
        using(Image imgFromClient = Image.FromStream(hpf.InputStream))
        { 
            string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory + 
                                    filePath.Replace("~/", "").Replace("/", "\\"); 
            Image.GetThumbnailImageAbort myCallbackCompressed = 
                                    new Image.GetThumbnailImageAbort(ThumbnailCallback); 
            using(Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width,
                                    imgFromClient.Height, myCallbackCompressed, IntPtr.Zero))
            {
                 imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg); 
            }
        }
    } 


    public static void SaveThumbImage(string imagePath, string filePath, 
                                      int width = 0, int height = 0)   
    {   
        using(Image originalImage = Image.FromFile(imagePath))
        {
            if (width > 0 && height > 0)   
            {   
                Image.GetThumbnailImageAbort myCallback = 
                      new Image.GetThumbnailImageAbort(ThumbnailCallback);   
                using(Image imageToSave = originalImage.GetThumbnailImage(width, height, 
                                    myCallback, IntPtr.Zero))
                {
                    imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);   
                }
            }   
            else   
            {   
                originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);   
            }   
        }   
     }