我正在編寫簡單的文本編輯器,並遇到保存問題。所以,我對於節省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