1. 程式人生 > >C# 刪除或修改檔案時提示檔案被佔用

C# 刪除或修改檔案時提示檔案被佔用

此問題可以使用下面三個方法解決問題.

方法1:在要進行檔案操作前將Image物件銷燬.

System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image);
image.Dispose();

方法2:就是在載入影象的時候用一種方法替代
System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);
System.Drawing.Image bmp = new System.Drawing.Bitmap(img.Width, img.Height, img.PixelFormat);

System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.DrawImage(img, 0, 0);
g.Flush();
g.Dispose();
img.Dispose();


方法3:

System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);

int byteLength = (int)fs.Length;
byte[] fileBytes = new byte[byteLength];
fs.Read(fileBytes, 0, byteLength);

//檔案流關閉,檔案解除鎖定
fs.Close();