C#File.Delete,另一个进程正在使用的文件

Vin*_*ent 5 c# error-handling

我在尝试删除图像文件时遇到问题.我总是得到一个错误:IOExeption未处理.访问被拒绝,因为该文件正被另一个进程使用.

我不知道可能是什么过程以及如何解决它.

private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {            
            Album album = GetAlbum(comboBox1.SelectedIndex);
            Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex);           

            txtPhotoPath.Text = Directory.GetCurrentDirectory() + "\\"  + photo.SPath;

            lblExtention.Text = photo.SExtention;
            txtPhotoTitle.Text = photo.STitle;
            pctrbFoto.Image = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr());
        }

private void btnChangePhoto_Click(object sender, EventArgs e)
{
            Album album = GetAlbum(comboBox1.SelectedIndex);
            Photo photo = GetPhoto(comboBox1.SelectedIndex, comboBox3.SelectedIndex);

            File.Delete("Albums\\Images\\" + photo.STitle + foto.SExtention);

            photo.SExtention = lblExtention.Text;
            photo.STitle = txtPhotoTitel.Text;
            Photo.SPath = txtPath.Text;

            File.Copy(photo.SPath, "Albums\\Images\\" + photo.STitle + photo.SExtention);

}

谢谢,Vinzcent


感谢大家的帮助.

我用过这个,现在效果很好


你的进程是使用文件的进程,你需要将image设置为null使用这样的东西:

var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath,GetHeight(photo.SPath,150)),GetfHeight(photo.SPath,150),null,new IntPtr());

pctrbFoto.Image = img;

img = null;

所以GC.Collect();

Sco*_*son 6

我看的第一个区域是你的GetPhoto方法.你有一个尚未关闭的StreamReader吗?如果您在删除之前对文件执行任何类型的I/O,请确保先关闭这些连接.GetPhoto()方法有什么作用?


Sad*_*egh 2

您的进程是使用 file 的进程,您需要将 image 设置为 null 使用如下所示:

using(var img = Image.FromFile(foto.SPath).GetThumbnailImage(GetWitdth(photo.SPath, GetHeight(photo.SPath, 150)), GetfHeight(photo.SPath, 150), null, new IntPtr()))
  pctrbFoto.Image = img;
Run Code Online (Sandbox Code Playgroud)

  • 一般来说,调用 GC.Collect 是一个坏主意:http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx 由于 Image 实现了 IDisposable,因此您应该调用 img.Dispose() ,或者(最好)使用“using”块。 (6认同)