我在哪里放置dispose()?

问题描述 投票:0回答:1

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

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

c# asp.net dispose streamreader streamwriter
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.