简单的问题因为我太愚蠢了。我正在使用streamreader和writer,它给了我一个例外,即该文件已被另一个进程使用。我知道我必须在某个地方设置一个.dispose()
。但我真的不知道在哪里。我太盲目了。
这是我的代码:
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sPath = @"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
Geht.Geht = DateTime.Now.ToString("hh:mm");
Geht.dtGeht = DateTime.Now;
sr.Dispose();
using (StreamWriter sw = new StreamWriter(sPath))
{
File.WriteAllText(sPath, string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};{4:hh:mm}", Geht.ID, Geht.User, Geht.Datum, Geht.Kommt, Geht.Geht));
}
}
我在这里得到错误:
File.WriteAllText(sPath, string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};{4:hh:mm}", Geht.ID, Geht.User, Geht.Datum, Geht.Kommt, Geht.Geht));
进程无法访问该文件,因为它正由另一个进程使用
你应该删除:
using (StreamWriter sw = new StreamWriter(sPath))
因为你实际上并没有使用sw
(它正在锁定文件)。
所以:
using (StreamWriter sw = new StreamWriter(sPath))
{
File.WriteAllText(sPath, string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};{4:hh:mm}", Geht.ID, Geht.User, Geht.Datum, Geht.Kommt, Geht.Geht));
}
会变成:
File.WriteAllText(sPath, string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};{4:hh:mm}", Geht.ID, Geht.User, Geht.Datum, Geht.Kommt, Geht.Geht));
简而言之,你的sw
锁定文件 - 使File.WriteAllText
无法写入它。
因此整个代码块可以是:
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sPath = @"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
cZeile Geht = null; // no point newing up an object since you are about to assign to it below
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
Geht.Geht = DateTime.Now.ToString("hh:mm");
Geht.dtGeht = DateTime.Now;
}
File.WriteAllText(sPath, string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};{4:hh:mm}", Geht.ID, Geht.User, Geht.Datum, Geht.Kommt, Geht.Geht));
}
请注意,using
将自动调用Dispose
上的sr
。