[英]How to delete file and that file is used by another process using C#
In my C# application I want to delete file in below scenario. 在我的C#应用程序中,我想在以下情况下删除文件。
OpenFileDialog and select any .jpg file. OpenFileDialog并选择任何.jpg文件。
Display that file in PictureBox. 在PictureBox中显示该文件。
Delete that file if needed. 如果需要,请删除该文件。
I already try while doing step 3 I set default Image to PictureBox just before delete but that is not work. 我已经在执行第3步时尝试过,在删除之前将默认Image设置为PictureBox,但这是行不通的。
How can I delete file? 如何删除文件? Please suggest me. 请给我建议。
// Code for select file.
private void btnSelet_Click(object sender, EventArgs e)
{
if (DialogResult.OK == openFileDialog1.ShowDialog())
{
txtFileName.Text = openFileDialog1.FileName;
myPictureBox.Image = Image.FromFile(openFileDialog1.FileName);
}
}
// Code for Delete file
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
//myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Replacing the image sounds like a good idea - but don't forget to dispose of the old Image
that's still holding the file open (and will, by default, until that Image
is garbage collected - at some unknown time in the future): 更换图像听起来像是一个好主意-但不要忘了处理旧的Image
是仍然拿着文件打开(并会在默认情况下,直到Image
被垃圾回收-在未来的某未知时间):
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
var old = myPictureBox.Image;
myPictureBox.Image = Image.FromFile(System.IO.Directory.GetCurrentDirectory() + @"\Images\defaultImage.jpg");
old.Dispose();
System.IO.File.Delete(txtFileName.Text);
MessageBox.Show("File Delete Sucessfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(It may also be possible to Dispose
of the Image
directly without replacing the image for the PictureBox
- it depends on what else you're going to do after deletion - eg if the form on which the PictureBox
appears is closing that you may want to let that happen first and then just directly dispose of the image). (也有可能直接Dispose
Image
而不用替换PictureBox
的图像-这取决于删除后您还要执行的其他操作-例如,如果PictureBox
出现的窗体正在关闭,您可能想要让它先发生,然后直接处理图像)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.