gpt4 book ai didi

c#-3.0 - 如何在应用程序运行时删除文件

转载 作者:行者123 更新时间:2023-12-04 06:40:30 24 4
gpt4 key购买 nike

我开发了一个 C# 应用程序,在应用程序中,用户为每条记录选择一张照片。然而,用户还应该能够用较新的照片更改预先选择的照片。当用户更改照片时,应用程序首先从应用程序目录中删除旧照片,然后复制新照片,但是当它这样做时,应用程序会给出一个异常(exception),因为该文件被应用程序使用,因此在应用程序运行时无法删除它运行。有没有人知道如何解决这个问题? 感谢您的帮助

这是异常(exception)

The process cannot access the file 'D:\My Projects\Hawkar'sProject\Software\Application\bin\Debug\Photos\John Smith.png' because it is being used by another process.


 //defining a string where contains the file source path
string fileSource = Open.FileName;

//defining a string where it contains the file name
string fileName = personNameTextBox.Text + ".png" ;

//defining a string which specifies the directory of the destination file
string fileDest = dir + @"\Photos\" + fileName;

if (File.Exists(fileDest))
{

File.Delete(fileDest);
//this is a picturebox for showing the images
pbxPersonal.Image = Image.FromFile(dir + @"\Photos\" + "No Image.gif");
File.Copy(fileSource, fileDest);
}
else
{
File.Copy(fileSource, fileDest);

}
imageIDTextBox.Text = fileDest;

最佳答案

首先,你的代码不好。
仅当当前没有图像(否则)时才会复制新图像。
但是如果有旧图像,你只删除这个图像,但永远不要复制新的(如果)。

代码最好看起来像这样:

if (File.Exists(fileDest))
{
File.Delete(fileDest);
}

File.Copy(fileSource, fileDest);
imageIDTextBox.Text = fileDest;

此代码应该可以工作,但如果您收到文件已在使用中的异常,您应该检查您使用该文件的“位置”。也许您正在程序启动时读取文件。如果有一些句柄打开,请检查您正在访问这些用户文件的程序的所有部分。

关于c#-3.0 - 如何在应用程序运行时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4303782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com