0

my question is why I am unable to acces local variable sw here... I am attempting to write text to a file to save it but the sw.WriteLine(element); in the foreach loop is unable to use sw.

public void SaveToFile(List<string>lines)
{
    FileStream fs;
    StreamWriter sw;
    try
    {
        fs = new FileStream(fileName,
                       FileMode.OpenOrCreate, FileAccess.Write);
        sw = new StreamWriter(fs);
    }
    catch (IOException)
    { MessageBox.Show("Error opening file"); }

    /////////////////////////////////////////////////////////////////////////
    try
    {
        foreach (string element in lines)
        {
            sw.WriteLine(element);
        }
    }
    catch (IOException)
    { MessageBox.Show("Error writing to file"); }
    ////////////////////////////////////////////////////////////////////////

    try
    {
        if (sw != null)
            sw.Close();
    }
    catch (IOException)
    { MessageBox.Show("Error closing file"); }

}
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    you could be using it before its assigned: `FileStream` or `StreamWriter` could throw. – Daniel A. White Oct 18 '16 at 17:49
  • 1
    consider using the `IDisposable` pattern. – Daniel A. White Oct 18 '16 at 17:49
  • 1
    Your `try` blocks are [separate scopes](http://stackoverflow.com/q/94977/205233) - nothing you initialize inside one is available inside the others. – Filburt Oct 18 '16 at 17:52
  • 3
    Your logic is "if the file cannot be opened, try to write to it anyways". This seems like a bad idea. – Eric Lippert Oct 18 '16 at 18:14
  • @GrantWinney I said *initialize*, not *define*. – Filburt Oct 18 '16 at 18:47
  • thanks for the answers, i don't see this as a duplicate question since i was unaware of the try blocks being seperate scopes as Filburt said, I figured this out about 2 hours after i posted the question. but does anyone have an idea as to how else to do it? place the other try blocks inside of the first? – Pepijn Claessens Oct 19 '16 at 07:35

0 Answers0