[問題] 檔案複製問題

看板C_Sharp作者 (狐狸)時間15年前 (2010/04/14 16:55), 編輯推噓1(107)
留言8則, 3人參與, 最新討論串1/1
我寫了一個程式 用來做產品的銷售管理 問題發生在編輯產品資訊的部份 我的想法是這樣 讓使用者選擇產品的圖片 然後先複製一份該圖片到指定資料夾 再呼叫複製的該圖片去做顯示 以下為部份程式碼: //************************************************************** private string copyGraphics(string filePath, string directory) { string destiFilePath = Path.Combine(directory, Path.GetFileName(filePath)); if (Path.GetFullPath(destiFilePath) == filePath) return filePath; else { File.Copy(filePath, destiFilePath, true); return destiFilePath; } } //************************************************************** 問題發生在File.Copy()的部份 假設我先選擇了一張圖片A 再改成選擇圖片B (A B都在指定資料夾外) 也就是先File.Copy(A, ..., ...) 再File.Copy(B, ..., ...) 這時如果我再選擇圖片A,也就是會再執行File.Copy(A, ..., ...)的時候 就會出現IOException 由於另一個處理序正在使用檔案 '.\..\..\data\pics\Jay.jpg',所以無法存取該檔案。 這部份我試了很久都找不到解決辦法 麻煩各位高手指點一下 感激! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.44.27

04/14 17:21, , 1F
此時目的端的圖片A是否已經在顯示,所以要再copy過去會Erro
04/14 17:21, 1F

04/14 17:39, , 2F
回樓上 應該不是 因為再次File.Copy(A)時,正在顯示的是B
04/14 17:39, 2F
sorry 經過我繼續測試的結果 一樓的懷疑應該是對的 但是我還是不知道錯在何處 只好放上更多程式碼 if (fileOpen.ShowDialog() == DialogResult.OK) { //copy the picture to the specified directory string picPath = copyGraphics(fileOpen.FileName, fileOpen.InitialDirectory); //update system model updateModelWhenPicChanged(PdtStorage.Products [LBox_products_high.SelectedIndex], picPath); pdtChanged = true; //update visual updateVisualWhenPicChanged(picBox_high, PdtStorage.Products [LBox_products_high.SelectedIndex]); } //************************************************************** private void updateVisualWhenPicChanged(PictureBox picBox, product pdt) { picBox.Image = null; picBox.Image = Image.FromFile(pdt.PicturePath); } //************************************************************** 如果把updateVisualWhenPicChanged()註解掉就沒有前述的問題了 所以問題應該是發生在這 但是這我就不懂了 為什麼做前述操作(A-B-A)的時候 指定資料夾的圖片會在使用中呢? 困擾阿~ ※ 編輯: angelfox 來自: 140.112.44.27 (04/14 18:35)

04/14 18:29, , 3F
在顯示的過程中 不要讓使用者點圖片
04/14 18:29, 3F

04/14 18:30, , 4F
IO也是要花成本的
04/14 18:30, 4F
※ 編輯: angelfox 來自: 140.112.44.27 (04/14 18:46)

04/14 22:15, , 5F
MSDN:Image.FromFile 檔案會保持鎖定,直到已處置 Image
04/14 22:15, 5F

04/14 22:21, , 6F
Image != null時 ,先picBox.Image.Dispose(); 看看
04/14 22:21, 6F

04/15 10:20, , 7F
原來如此 我以為picBox.Image = null就行 原來要dispose
04/15 10:20, 7F

04/15 10:20, , 8F
問題已解決了 太感謝各位!!
04/15 10:20, 8F
文章代碼(AID): #1BnOBcju (C_Sharp)