C# 进程无法访问该文件,因为它正被另一个进程使用(文件对话框)

标签 c# windows winforms visual-studio-2008

我有一个正在用日志信息更新的富文本框。有一个按钮可以将日志输出保存到文件中。当我使用下面的代码尝试将输出保存到文件时,我收到“该进程无法访问该文件,因为它正被另一个进程使用”的异常。我不确定为什么会收到此异常。它发生在我在对话框中创建的新文件上。它发生在我尝试将信息保存到的任何文件上。

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,这可能会打开具有给定名称的文件并将数据保存到其中。

我想第一个电话是不必要的。

关于C# 进程无法访问该文件,因为它正被另一个进程使用(文件对话框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246250/

相关文章:

android - react 原生 : Could not initialize class org. codehaus.groovy.reflection.ReflectionCache

.net - 数据 GridView 自动调整大小

c# - asp.net aspx 的标记验证

windows - 以编程方式获取 GPU 处理器使用情况

c# - 您如何快速找到接口(interface)方法的实现?

c++ - 带有 SetParent() 的 WS_EX_LAYERED 不显示窗口

.net - 获取ListBox显示高度

c# - 避免 .NET (C#) 项目中的重复图标资源

c# - 它是一种获取SQL关键字(保留字)的编程方式吗?

c# - 使用箭头键控制菜单并输入