c# - 删除另一个文件后无法创建另一个文件,因为它已被另一个进程使用

标签 c# file process

我知道这是一个很常见的问题,我尝试过使用进程,但它不起作用。所以,我希望用户能够上传照片,创建自己的头像。我所做的是拍摄选定的照片,调整其大小,然后裁剪它并将其保存在应用程序/bin 中。如果他再次选择另一张照片,我会删除第一张照片并创建另一张照片。删除照片后,出现此错误:

The process cannot access the file : 'C:\.." because it is being used by another process. 

代码:

  private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        try
        {

         Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
         dlg.Title = "Open Image";
         dlg.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";

            if (dlg.ShowDialog() == true)
            {
                string fileName = dlg.FileName;
                Uri uri = new Uri(fileName, UriKind.RelativeOrAbsolute);
                BitmapImage bit = new BitmapImage(uri);
                Bitmap b = new Bitmap(fileName);
                b = ResizeImage(b, 100, 100);
                b = CropCircleImage(b);

              string path = System.AppDomain.CurrentDomain.BaseDirectory + @"UserPhotos\";
              string file =Button.Content.ToString()+".bmp";

                if (File.Exists(path + file))
                    File.Delete(path + file);

              //after it gets out from the if statement, I get the error
                  b.Save(path + file);       

                Uri newuri = new Uri(path + file, UriKind.RelativeOrAbsolute);

               ((ButtonLogin)sender).Image= new BitmapImage(newuri);

最佳答案

这可能是因为您正在更新特定用户的图像,并且您试图删除旧图像并在旧图像正在使用时上传更新的图像。尝试“取消引用”旧的,然后上传新的。

对取消引用这个词感到抱歉。我的意思是检查该图像是否在其他地方使用并被锁定。如果是,请解锁并上传新的。

关于c# - 删除另一个文件后无法创建另一个文件,因为它已被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960616/

相关文章:

c# - 获取非继承属性

c# - 如何通过 TCP 在 C# 中发送文件夹?

c - C语言程序从文件中读取信息

JAVA - 访问不同子文件夹中的文件

.net - 如何获取当前的ProcessID?

c++ - 如何禁止普通用户终止进程?

c# - 为什么 System.IO.File 在文件确实存在时返回 false?

c# - Gridview DataKey 的空引用异常

c# - 不安全的指针操作

C#启动一个进程后,进程立即退出