秋季尝试更改picturebox图像c#

秋季尝试更改picturebox图像c#,c#,C#,1.答案: 进程无法访问该文件,因为另一进程正在使用该文件 此文件在pictureBox中使用,我想更改pictureBox图像,并将文件交换为新文件 我找到了使用的答案,如下所示: 1. System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName)); 但它不起作用,因为我需要图片始终可见。。 任何解决方案,我都会很高兴。谢谢问题在于,一旦图片加载到PictureBox中,它会保留文件的句柄。所以你不能复制它 要

1.答案:

进程无法访问该文件,因为另一进程正在使用该文件

此文件在
pictureBox
中使用,我想更改
pictureBox
图像,并将文件交换为新文件

我找到了使用
的答案,如下所示:

1. System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));
但它不起作用,因为我需要图片始终可见。。
任何解决方案,我都会很高兴。谢谢

问题在于,一旦图片加载到
PictureBox
中,它会保留文件的句柄。所以你不能复制它

要释放文件句柄,您将需要释放它

但是,如果您想在尝试复制(我认为您正在尝试这样做)时保持图像的活动状态(视觉显示),则必须加载图像,然后以某种方式克隆它,然后释放句柄

因此,我相信在加载图像时,以下模式应该适用于您

// before copying the file make sure the file handle is released
// by calling dispose
if(PictureBox1.Image != null)
{
     PictureBox1.Image.Dispose();
     PictureBox1.Image = null;
} 

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\",newFileName));
最后注意事项:完成图像后,请确保 处理它。也就是说,如果您创建了它,则需要对其进行处理


尝试加载映像,克隆它,然后按如下方式发布

// before loading any new image lets release any previously displayed imaged
if(PictureBox1.Image != null)
{
     PictureBox1.Image.Dispose();
     PictureBox1.Image = null;
} 

// this loads the image, copies it, then closes the handle
using (var bmpTemp = new Bitmap("image_file_path"))
{
    PictureBox1.Image = new Bitmap(bmpTemp);
}

...

// It should be safe to copy the file now, as the handle should be released
File.Copy(fileName, Path.Combine(@"C:\images\",     newFileName));
通过这种方式释放文件句柄,您可以处理加载到内存中的图像

using (Bitmap temp = new Bitmap(fileName))
    pictureMain.Image = new Bitmap(temp);

发布问题时,请检查a)格式,b)语言标记是否加载图片一次?您需要确保位图不再被引用。这比看起来难多了谢谢你的回答帮了我大忙
using (Bitmap temp = new Bitmap(fileName))
    pictureMain.Image = new Bitmap(temp);
System.IO.File.Copy(fileName, Path.Combine(@"C:\images\", newFileName));