简体   繁体   English

c#ASP.NET如何删除另一个进程“正在使用”的文件?

[英]c# ASP.NET How do i delete a file that is “in use” by another process?

I'm loading a file: 我正在加载文件:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);

Now I would like to save the image: 现在,我想保存图像:

img.Save(SavePath);

This works.. Unless FilePath == SavePath , then it decides to give me the error: 除非FilePath == SavePath ,否则它将决定给我错误:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

So I tried to delete the file, right after opening it: 因此,我尝试在打开文件后立即删除该文件:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);
File.Delete(FilePath);

And it gives me the error: 它给了我错误:

System.IO.IOException: The process cannot access the file 'filename.jpg' because it is being used by another process.

So... How can I modify an existing file, that's "in use" when its not in use by anyone? 所以...如果某人不使用该文件,我该如何修改该文件?

The image will remain locked until it is disposed ( See here ). 图像将一直保持锁定,直到将其丢弃( 请参阅此处 )。

The file remains locked until the Image is disposed. 该文件将保持锁定,直到处理完映像为止。

You'll have to save the image somewhere else (or copy its contents out) and then dispose the opened image via using a using clause. 您必须将图像保存在其他位置(或复制其内容),然后使用using子句处理打开的图像。

Example: 例:

using(Image image1 = Image.FromFile("c:\\test.jpg"))
{
    image1.Save("c:\\test2.jpg");
}

System.IO.File.Delete("c:\\test.jpg");
System.IO.File.Move("c:\\test2.jpg", "c:\\test.jpg");

you can either use Memory stream or put it in byte[] array 您可以使用内存流,也可以将其放入byte []数组中

http://www.vcskicks.com/image-to-byte.php http://www.vcskicks.com/image-to-byte.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM