簡體   English   中英

File.Copy“該進程無法訪問該文件 <filename> 因為它正在被另一個進程使用

[英]File.Copy "The process cannot access the file <filename> because it is being used by another process

我的代碼是這樣的:

using (var openFileDialogForImgUser = new OpenFileDialog())
{
    string location = null;
    string fileName = null;
    string sourceFile = null;
    string destFile = null;
    string targetPath = @"..\..\Images";
    openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
    openFileDialogForImgUser.InitialDirectory = @"D:\My Pictures";
    var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
    if (openFileResult == DialogResult.OK)
    {
        using (var formSaveImg = new FormSave())
        {
            var saveResult = formSaveImg.ShowDialog();
            if (saveResult == DialogResult.Yes)
            {
                imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
                fileName = openFileDialogForImgUser.FileName;
                location = Path.GetDirectoryName(fileName);

                sourceFile = System.IO.Path.Combine(location, fileName);
                destFile = System.IO.Path.Combine(targetPath, fileName);

                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                System.IO.File.Copy(sourceFile, destFile, true); /* error occurs at this line */

            }
            else
                openFileDialogForImgUser.Dispose();
        }
    }
}

我要執行的操作是提示用戶在OpenFileDialog中選擇一個圖像,然后將該圖像復制到另一個目錄(特別是targetPath)。 除了這一行外,其他所有東西似乎都正常運行: System.IO.File.Copy(sourceFile, destFile, true);

它說該文件專用於另一個進程。 我選擇的任何圖像都會發生這種情況。

我正在嘗試研究其他人針對此問題的解決方案---我必須終止(或等待)正在使用我的文件的過程。 如果是這樣,我該怎么做? 或者,如果這不是答案,我該怎么辦? 請注意,這是我的C#解決方案中處理圖像文件的唯一代碼。

我認為您的問題涉及未正確處置Bitmap對象。 如果創建的位圖可以從文件中讀取並且不進行處理,則文件將保持打開和鎖定狀態。

這里有幾個鏈接:

用C#處理OpenFileDialog?

C#:調用Bitmap.save()之后將Dispose()一個Bitmap對象?

正如我在這個答案中所指出的那樣https://stackoverflow.com/a/18172367/253938我使用Bitmap和磁盤文件的經驗是,最好永遠不要讓Bitmap打開文件。 而是,將文件讀入字節數組,然后使用ImageConverter將其轉換為Image。

完成后,您需要關閉文件。 使用.Close()屬性關閉文件。

打開文件以供讀取/使用后,它會打開一個后台進程。 為了結束該過程,您還需要使用.Close()以編程方式將其關閉

因此,您的代碼需要在代碼底部具有yourFile.Close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM