Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#ASP.NET如何删除一个名为;“正在使用”;通过另一个过程?_C#_File Io - Fatal编程技术网

c#ASP.NET如何删除一个名为;“正在使用”;通过另一个过程?

c#ASP.NET如何删除一个名为;“正在使用”;通过另一个过程?,c#,file-io,C#,File Io,我正在加载一个文件: System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath); 现在我想保存图像: img.Save(SavePath); 这很有效。。除非FilePath==SavePath,否则它决定给我错误: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. System.IO.IOExce

我正在加载一个文件:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);
现在我想保存图像:

img.Save(SavePath);
这很有效。。除非
FilePath==SavePath
,否则它决定给我错误:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
System.IO.IOException: The process cannot access the file 'filename.jpg' because it is being used by another process.
因此,我试图在打开文件后立即删除该文件:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);
File.Delete(FilePath);
这给了我一个错误:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
System.IO.IOException: The process cannot access the file 'filename.jpg' because it is being used by another process.
所以。。。
如何修改任何人都不使用的“正在使用”的现有文件?

您可以使用内存流或将其放入byte[]数组中


图像将保持锁定状态,直到被释放()

在释放图像之前,文件将保持锁定状态

您必须将图像保存到其他地方(或将其内容复制出来),然后使用
using
子句处理打开的图像

例如:

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");

究竟为什么文件会保持锁定状态?它是打开的,读入内存,然后关闭的?使图像类型成为PITA。@Justin808:我不确定推理是否正确,但文档中说是出于设计,请参见上面的编辑。这是可行的,但下面的链接说明了如何在不使用临时文件的情况下执行此操作。