删除其他进程正在使用的文件

问题描述 投票:22回答:6

我正在尝试以编程方式删除文件,但该文件显然正在被另一个进程使用(这恰好是我的程序)。基本上,程序通过使用FromUri来创建一个Bitmap来加载一个文件夹中的图像,然后将其加载到一个Image数组中,该数组又成为一个stackpanel的子项。不是很有效,但它的工作原理。

我已经尝试清除stackpanel的子节点,并使数组中的图像为null,但我仍然得到IOException告诉我该文件正由另一个进程使用。

有没有其他方法从我的应用程序的进程中删除该文件?

c# wpf file process delete-file
6个回答
21
投票

要在加载后释放图像文件,您必须通过设置BitmapCacheOption.OnLoad标志来创建图像。一种方法是这样做:

string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();

虽然设置BitmapCacheOption.OnLoad适用于从本地文件Uri加载的BitmapImage,但这是无法记录的。因此,通过设置StreamSource属性而不是UriSource,可能更好或更安全的方法是从FileStream加载图像:

string filename = ...
BitmapImage image = new BitmapImage();

using (var stream = File.OpenRead(filename))
{
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = stream;
    image.EndInit();
}

93
投票

它可能是垃圾收集问题。

System.GC.Collect(); 
System.GC.WaitForPendingFinalizers(); 
File.Delete(picturePath);

7
投票

另一种方法是删除文件。使用FileStream类加载文件并通过stream.Dispose();释放文件。它永远不会给你异常“进程无法访问文件',因为它正在被另一个进程使用。”

using (FileStream stream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read))
{
    pictureBox1.Image = Image.FromStream(stream);
     stream.Dispose();
}

 // delete your file.

 File.Delete(delpath);

2
投票
var uploadedFile = Request.Files[0]; //Get file
var fileName = Path.GetFileName(uploadedFile.FileName);  //get file name
string fileSavePath = Server.MapPath(fileName); //get path
uploadedFile.SaveAs(fileSavePath); //saving file
FileInfo info = new FileInfo(fileSavePath);//get info file
//the problem ocurred because this, 
FileStream s = new FileStream(fileSavePath, FileMode.Open); //openning stream, them file in use by a process
System.IO.File.Delete(fileSavePath); //Generete a error
//problem solved here...
s.Close();
s.Dispose();
System.IO.File.Delete(fileSavePath); //File deletad sucessfully!

-1
投票

我有类似的问题。唯一的区别是我使用Binding(MVVM Pattern)。没有什么工作,然后我删除了一切,并尝试绑定Mode=OneWayGC.Collect()之前调用File.Delete(path),它最终工作。


-1
投票

我遇到过同样的问题。我遇到的问题是openFileDialog和saveFileDialog具有以下设置:

MyDialog.AutoUpgradeEnabled = false;

我评论了这条线并且它已经解决了。

© www.soinside.com 2019 - 2024. All rights reserved.