Search code examples
c#text-filestextwriter

Cannot write to a closed TextWriter


I am trying to write text to my txt file. After the first write the application crash with error

Cannot write to a closed TextWriter

My list contains links that the browser opens and I want to save all of them in txt file (like a log).

My code:

FileStream fs = new FileStream(
                    "c:\\linksLog.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);

for (int i = 0; i < linksList.Count; i++)
{
    try
    {
        System.Diagnostics.Process.Start(browserType, linksList[i]);
    }
    catch (Exception) { }

    using (sw)
    {
        sw.WriteLine(linksList[i]);
        sw.Close();
    }

    Thread.Sleep((int)delayTime);

    if (!cbNewtab.Checked)
    {
        try
        {
            foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName == getProcesses)
                {
                    process.Kill();
                }
            }
        }
        catch (Exception) { }
    }
}

Solution

  • You're in a for loop, but you close and dispose of your StreamWriter on the first iteration:

    using (sw)
    {
        sw.WriteLine(linksList[i]);
        sw.Close();
    }
    

    Instead, remove that block, and wrap everything in one using block:

    using (var sw = new StreamWriter(@"C:\linksLog.txt", true)) {
        foreach (var link in linksList) {
            try {
                Process.Start(browserType, list);                        
            } catch (Exception) {}
    
            sw.WriteLine(link);
    
            Thread.Sleep((int)delayTime);
    
            if (!cbNewtab.Checked) {
                var processes = Process.GetProcessesByName(getProcesses);
    
                foreach (var process in processes) {
                    try {
                        process.Kill();
                    } catch (Exception) {}
                }
            }
        }
    }