Skip to main content
 首页 » 编程设计

c#之压缩完成后立即删除图像文件。如何

2024年02月13日14qq78292959

我有一个网站,允许用户通过上传表单在服务器上上传一些图片。上传此图像时,asp.net 服务应压缩该特定图像。压缩图像已经很好用了,但我想在压缩完成后从服务器的磁盘中删除原始图像。

请花点时间看看我下面的代码:

 if (fileUl.PostedFile.ContentType == "image/jpeg" || fileUl.PostedFile.ContentType == "image/png")  
 { 
    fileUl.SaveAs(fullPath); 
    System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath);  
    compressImage(destinationPath, image, 40); 
     System.IO.File.Delete(fullPath); 
 
 } // nested if 

如果我尝试运行上面的代码,我会得到

System.IO.IOException: The process cannot access the file [filepath] because it is being used by another process.

我其实很期待,因为我认为这是因为,当下一行代码想要删除该图像时,服务器仍在压缩该图像(我认为就是这样)。所以我的问题是:

如何等待压缩完成,然后运行“删除”代码?

请您参考如下方法:

using (System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
{ 
  //DO compression; 
} 
System.IO.File.Delete(fullPath); 

最好在压缩函数中完成所有操作:

public void DoCompression(string destination, string fullPath, int ratio) 
{ 
    using (System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
    { 
      //DO compression by defined compression ratio. 
    } 
} 

调用函数可能如下所示:

DoCompression(destinationPath, fullPath, 40); 
DoCompression(destinationPath, fullPath, ??); 
 
System.IO.File.Delete(fullPath);