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

标签 c# asp.net image

我有一个网站,允许用户通过上传表单在服务器上上传一些图片。上传此图像时,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);

关于c# - 压缩完成后立即删除图像文件。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459802/

相关文章:

c# - 当参数是 C# 中的值或引用类型时调用函数?

c# - 如何通过SqlConnection获取最后执行的SQL查询?

c# - UserManager 不断抛出 System.ArgumentNullException

android - 需要将图像从 res 文件夹复制到画廊/文件夹

image - PhoneGap 中的内存管理

c# - 如何将日期时间变量与 lambda 表达式进行比较?

c# - 使用 Dispatcher.Invoke 从非主线程更改 WPF 控件

php - 使用 2 个文本字段将多个图像上传到数据库

.net - Asp net 验证错误消息从不显示

c# - 加载 MvcModule 类型的模块 'Ninject.Web.Mvc.MvcModule' 时出错