Куда мне положить dispose ()? - PullRequest
       16

Куда мне положить dispose ()?

0 голосов
/ 13 сентября 2018

простой вопрос, потому что я слишком тупой.Я использую 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 голосов
/ 13 сентября 2018

Вы должны удалить:

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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...