我正在编写简单的文本编辑器,并遇到保存问题。所以,我对于节省2码,一个是保存文件中使用按钮和其他CTRL + S键盘快捷键,使用按钮一切完美保存时,但是当我用快捷键拯救我得到这个错误:c#streamwriter“进程无法访问文件”错误,即使它关闭并处理
"process cannot access file because it's used by another process"
这里是我的按钮的代码保存:上面的`
saveFileDialog1.FileName = currentname;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(saveFileDialog1.OpenFile());
writer.WriteLine(richTextBox1.Text);
writer.Dispose();
writer.Close();
//so i have tabs in my editor so user can switch between them.
//and this is the only way i found which tab is opened now.
for (int i = 0; i < labels.Count; i++)
{
//i created new class that holds some variables including "isUsed"
//and Label itself.
if (labels[i].isUsed)
{
labels[i].Text = Path.GetFileName(saveFileDialog1.FileName);
labels[i].setText(labels[i].Text);
labels[i].path = saveFileDialog1.FileName;
break;
}
}
}`
脚本工作正常,但下面的脚本不:
public void save(){
bool found = false;
//that is class i made.
AdvancedLabel label = new AdvancedLabel();
//I hold all tabs in "Labels" List.
for (int i = 0; i < labels.Count; i++)
{
//so if loop found the tab that is opened now...
if (labels[i].isUsed)
{
label = labels[i];
found = true;
break;
}
}
if (found)
{
try
{
label.label.Text.Remove(label.label.Text.Length - 1);
//here i always get this error.
StreamWriter writer = new StreamWriter(label.path);
writer.WriteLine(richTextBox1.Text);
label.setText(label.Text.Remove(label.Text.Length - 1));
writer.Dispose();
writer.Close();
}
catch (Exception e)
{
status.Text = "status: " + e.Message + ". Failed to save :(";
}
}
}
以下是完整的错误:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\nika\Desktop\dd.html' because it is being used by another process.
编辑:
的感谢你们,我的理解,我应该使用 “使用” 的声明,这里是啥子,我想出了:
我忘了提及我也打开文件使用stramreader。我将其改为“使用”语句,但同样的事情发生,即使我现在正在使用:File.appendalltext语句。这也适用,但只有当我用按钮保存。
这是我如何改变它(文件首战没有作家):`
using (var sr = new StreamReader(openFileDialog1.FileName))
{
bool found = false;
for (int i = 0; i < labels.Count; i++)
{
if (labels[i].path == openFileDialog1.FileName)
{
found = true;
break;
}
}
if (!found)
{
richTextBox1.Text = "";
richTextBox1.Text = sr.ReadToEnd();
spawnLabel();
}
}`
PS(这听起来如此愚蠢)
为@GauravKP建议:
任何帮助将不胜感激!谢谢!
- 尼克。
那么,有什么错误,你实际上得到? – Jim
@Jim在mscorlib.dll中发生未处理的异常类型'System.IO.IOException' 附加信息:进程无法访问文件'C:\ Users \ nika \ Desktop \ dd.html',因为它正在被使用通过另一个进程。 – Nick
为什么downvote?至少可以解释,所以我不会在将来做这种类型的错误! – Nick