我必须在哪里放置dispose()?

时间:2018-09-13 12:03:21

标签: c# asp.net dispose streamreader streamwriter

一个简单的问题,因为我太傻了。我正在使用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));

该进程无法访问该文件,因为该文件正在被另一个进程使用

1 个答案:

答案 0 :(得分:6)

您应该删除:

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

相关问题