,所以我做了一個簡單的項目中,當我點擊一個按鈕的圖片編輯從文件夾文件中獲取的圖像,但是當我想刪除包含圖像的文件夾,它給了我一個錯誤。代碼如下刪除文件夾,但是該進程無法訪問該文件,因爲正在使用
private void button1_Click(object sender, EventArgs e)
{
string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
pictureEdit1.Image = Image.FromFile(pathx);
}
private void button2_Click(object sender, EventArgs e)
{
string dir = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage";
try {
if (Directory.Exists(dir))
{
//////give me an error in here///////
Directory.Delete(dir, true);
}
else
{
MessageBox.Show("folder not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
這樣做的目的,是在我的主要項目中,高速緩存的目的。所以我從服務器應答到本地後從某個文件夾中獲取圖像。當我想關閉主項目,我需要清除緩存或文件夾
更新
這是更好的替代1或備用2(處置)
private void button1_Click(object sender, EventArgs e)
{
string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
//alternate1
using (FileStream stream = new FileStream(pathx, FileMode.Open, FileAccess.Read))
{
pictureEdit1.Image = Image.FromStream(stream);
//stream.Dispose();
}
//alternate2
//Image img = new Bitmap(pathx);
//pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
//img.Dispose();
}
[IOException的可能重複:該過程,因爲它是被另一個不能訪問該文件「文件路徑」過程(http://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being) –
也許是因爲你是顯示在它預覽窗口,因此它正在被訪問。如果正在使用它,你不能刪除它? – Icewine
@chopperfield「問題」是GDI +圖像使文件保持打開狀態。處置它,你嘗試從一個MemoryStream –