[英]C# The process can't access the file because it is being used by another process (File Dialog)
I have a rich text box that is being updated with log information. 我有一个富文本框,正在使用日志信息进行更新。 There is a button to save the log output to a file.
有一个按钮可以将日志输出保存到文件中。 When I use the code below to try to save the output to a file, I receive "The process can't access the file because it is being used by another process" exception.
当我使用下面的代码尝试将输出保存到文件时,我收到“进程无法访问该文件,因为它正被另一个进程使用”异常。 I am not sure why I am receiving this exception.
我不知道为什么我收到这个例外。 It happens on new files that I create in the dialog.
它发生在我在对话框中创建的新文件中。 It happens on any file I try to save the information to.
它发生在我尝试保存信息的任何文件上。
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());
}
}
It seems the same file is opened twice. 似乎同一个文件打开两次。 First you create it using:
首先使用以下方法创建它:
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
Then you pass the same file name to this.logWindow.SaveFile
, which presumably opens the file with the given name and saves data to it. 然后将相同的文件名传递给
this.logWindow.SaveFile
,它可能会打开具有给定名称的文件并将数据保存到该文件中。
I guess the first call is unnecessary. 我想第一次电话是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.