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

时间:2014-04-09 11:05:26

标签: 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);

2 个答案:

答案 0 :(得分:2)

简单地说,您的进程或其他进程已打开文件并将其锁定,以便您的程序无法打开该文件。通常,当由于编码错误而无法正确关闭文件时会发生这种情况。

代码中的错误可能不在您显示的代码中。最有可能的错误是您未显示的代码。打开文件但无法关闭文件的代码。

如果您无法确定哪个进程对文件具有锁定,则可以使用Process Monitor或Process Explorer等调试工具。这些工具都可以显示哪个进程锁定文件。

答案 1 :(得分:2)

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

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