How do I close results file on failed test? Using Webdriver, c#
<p>I'm trying to create a customised results file for tests using Selenium Webdriver in c#.</p>

<p>I'm writing the results to a csv file, and closing it at the end.</p>

<p>The problem is that if the test fails and doesn't complete, the file is never closed, and therefore I don't get the results.</p>

<p>I've tried putting the file.Close(); in the Teardown section, but that doesn't work because "file" does not exist in that context. I can't see a way to pass it in.</p>

<p>I also tried setting up the new StreamWriter file in Setup - which was fine to do, but didn't help close it at the end.</p>

<p>I have searched on here and a general google search.</p>

<p>Here is a sample of what works - when it all passes (all in one place - different classes in test).</p>

<p>I want to be able to move the file.Close(); to where it will run regardless of whether it's passed or not.</p>

<pre><code>    [TearDown]
    public void TeardownTest()
    {
        try
        {
            driver.Quit();
        }
        catch (Exception)
        {
            // Ignore errors if unable to close the browser
        }
        Assert.AreEqual("", verificationErrors.ToString());

     //   file.Close();
     // this is where it doesn't work if I put it here
    }

    [Test]
    public void TheTest()
    {           
        System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\results\test.csv", true);

        try
        {
            Assert.AreEqual("text", "text");
            file.WriteLine("{0},{1},{2}", "time", "test", "PASS");
        }
        catch (AssertionException e)
        {
            verificationErrors.Append(e.Message);
            file.WriteLine("{0},{1},{2}", "time", "test", "FAIL");
        }

        //do next step

        file.Close();
    }
</code></pre>