我的Asp.net MVC应用需要上传文件。在上传过程中,我想操纵新上传的文件。
public ActionResult Edit(int id, FormCollection collection) {
Block block = userrep.GetBlock(id);
foreach (string tag in Request.Files) {
var file = Request.Files[tag] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
string tempfile = Path.GetTempFileName()
file.SaveAs(tempfile);
// This doesn't seem to make any difference!!
// file.InputStream.Close();
if (FileIsSmallEnough(file)) {
// Will throw an exception!!
File.Move(tempfile, permanentfile);
} else {
GenerateResizedFile(tempfile, permanentfile);
// Will throw an exception!!
File.Delete(tempfile);
}
block.Image = permanentfile;
}
userrep.Save();
此代码段的问题在于,任何操作最初上载的文件的尝试都会生成IOException(“进程无法访问该文件,因为它正由另一个进程使用。”)当然,我可以通过复制来绕过这个问题而不是移动上传的文件,但一旦我有更好的选择,我仍然无法删除它。
有什么建议吗? 达菲
答案 0 :(得分:2)
正如您在评论中提到的,您从文件中加载Image
。 MSDN文档指出文件保持锁定状态,直到图像被丢弃。
http://msdn.microsoft.com/en-us/library/stf701f5.aspx
要处理图像,可以在实例上调用Dispose
方法,或使用using
语句的首选机制:
private bool FileIsSmallEnough()
{
using (Image i = Image.FromFile())
{
}
}
这应该可以解决问题。