[英]How to delete file and that file is used by another process using C#
在我的C#應用程序中,我想在以下情況下刪除文件。
OpenFileDialog並選擇任何.jpg文件。
在PictureBox中顯示該文件。
如果需要,請刪除該文件。
我已經在執行第3步時嘗試過,在刪除之前將默認Image設置為PictureBox,但這是行不通的。
如何刪除文件? 請給我建議。
// 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);
}
}
更換圖像聽起來像是一個好主意-但不要忘了處理舊的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);
}
}
(也有可能直接Dispose
Image
而不用替換PictureBox
的圖像-這取決於刪除后您還要執行的其他操作-例如,如果PictureBox
出現的窗體正在關閉,您可能想要讓它先發生,然后直接處理圖像)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.