当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - how to close a file and delete that image file?

问题描述:

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;

How to delete the image and thumbnail in other function? (Is it necessary to close that first or not?)

网友答案:

I'm guessing that you're trying to delete a file on disk if it already exists for this user upon asp.net upload of an image by that same user again.

This method will delete both image and thumbnail if they exist.

Keep your image creation activities separate from your image clean up activities to keep your intent clear and your code maintainable.

    // 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);
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: