如何关闭文件并删除该图像文件?

时间:2012-06-23 11:59:54

标签: c# asp.net system.drawing

Imagename = objUser.UserID + filename;
Imagepath = "D:\\Shop\\ShopMonkey\\Images" + Imagename;
FileUpload.SaveAs(Path.Combine(@"D:\ShopMonkey_Web_21-6-12\ShopMonkey\Images", Imagename));

objUser.UploadImagePath = Imagepath;
objUser.UploadImagename = Imagename;

System.Drawing.Image img1 = System.Drawing.Image.FromFile(Imagepath);

System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero);
 ThumbNailPath = "D:\\ShopMonkey_Web_21-6-12\\ShopMonkey\\ThumbNails" + Imagename;
bmp1.Save(Path.Combine(@"D:\ShopMonkey_Web_21-6-12\ShopMonkey\ThumbNails", Imagename));
objUser.UploadThumbnailPath = ThumbNailPath;

如何删除其他功能中的图像和缩略图? (是否有必要先关闭它?)

1 个答案:

答案 0 :(得分:1)

我猜你正在尝试删除磁盘上的文件,如果该用户已经存在该用户再次由同一用户上传图像。

此方法将删除图像和缩略图(如果存在)。

将您的图片创建活动与图片清理活动分开,以保持您的意图清晰,并且您的代码可维护。

    // replace with an entry loaded from a config file    
    const string ImageRoot = @"D:\ShopMonkey_Web_21-6-12\ShopMonkey"; 
    // replace this is your user instance
    object user = new object(); 
    string Imagename = objUser.UserID + filename;
    string uploadImagePath = Path.Combine(ImageRoot, "Images", Imagename);
    string thumbnailPath = Path.Combine(ImageRoot, "ThumbNails", Imagename);
    objUser.UploadImagePath = uploadImagePath;
    objUser.UploadImagename = Imagename;
    objUser.UploadThumbnailPath = thumbnailPath;
    // delete both if they exist
    if (File.Exists(uploadImagePath))
        File.Delete(uploadImagePath);
    if (File.Exists(thumbnailPath))
          File.Delete(thumbnailPath);
    // replace this with your uploaded file details
    object fileInfo = new object(); 
    using (System.Drawing.Image img1 = System.Drawing.Image.FromFile(uploadImagePath)) {
          img1.Save(uploadImagePath);
          using (System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero)) {
            bmp1.Save(thumbnailPath);
          }
          FileUpload.SaveAs(uploadImagePath);
    }