在我的程序中,我正在將文本文件信息加載到富文本框中。當用戶點擊清除按鈕時,我希望文件內容爲空,並在富文本框中再次顯示。但是,當我嘗試清除錯誤時彈出該文件已被使用。試圖清除文本文件時使用的文件
我不確定這是怎麼回事,我懷疑它與關閉流讀取器或創建一個新的。無論哪種方式,我不太確定。
有沒有人有任何想法這是怎麼回事?
代碼:
namespace FileLocationAutomation
{
public partial class ViewLog : Form
{
public ViewLog()
{
InitializeComponent();
}
#region Variables
string str = "";
#endregion
#region Ok Button
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Form Load
private void ViewLog_Load(object sender, EventArgs e)
{
//catch any exception
try
{
//load the log thats kept on the users machine into the rich text object
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Clear Log
//clear the log file and display it on the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}
}
查看File類中的靜態方法 – SLaks
看起來您正在使用StreamReader打開文件,然後嘗試執行一般文件寫入。如果你清除它,你不需要讀回一個空文件。 – Logarr
我知道你的'.Close()'在你的文件上,技術上我認爲應該沒問題,但是最好是將'StreamReader'變量包裝在'using'語句中以確保調用'.Dispose()'。看看它是否有幫助... – LB2