簡體   English   中英

C#進程無法訪問該文件,因為它正由另一個進程使用(文件對話框)

[英]C# The process can't access the file because it is being used by another process (File Dialog)

我有一個富文本框,正在使用日志信息進行更新。 有一個按鈕可以將日志輸出保存到文件中。 當我使用下面的代碼嘗試將輸出保存到文件時,我收到“進程無法訪問該文件,因為它正被另一個進程使用”異常。 我不知道為什么我收到這個例外。 它發生在我在對話框中創建的新文件中。 它發生在我嘗試保存信息的任何文件上。

private void saveLog_Click(object sender, EventArgs e)
{
            OnFileDialogOpen(this, new EventArgs());
            // Displays a SaveFileDialog so the user can save the Image
            // assigned to Button2.
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Text File|*.txt|Log File|*.log";
            saveFileDialog1.Title = "Save Log File";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                // Saves the Image via a FileStream created by the OpenFile method.
                System.IO.FileStream fs =
                   (System.IO.FileStream)saveFileDialog1.OpenFile();
                // Saves the Image in the appropriate ImageFormat based upon the
                // File type selected in the dialog box.
                // NOTE that the FilterIndex property is one-based.
                switch (saveFileDialog1.FilterIndex)
                {
                    case 1:

                        try
                        {
                            this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }


                        break;
                    case 2:

                        try
                        {
                            this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }

                        break;
                }

                fs.Close();
                OnFileDialogClose(this, new EventArgs());
            }
}

似乎同一個文件打開兩次。 首先使用以下方法創建它:

System.IO.FileStream fs =
                   (System.IO.FileStream)saveFileDialog1.OpenFile();

然后將相同的文件名傳遞給this.logWindow.SaveFile ,它可能會打開具有給定名稱的文件並將數據保存到該文件中。

我想第一次電話是不必要的。

暫無
暫無

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

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