Question

I'm trying to find out if I can close a stream like this inside a using statement and open another?

Here is the code:

string combined = Path.Combine(path, some + ".txt");
if (File.Exists(combined))
{
    using (TextReader obj2 = new StreamReader(combined))
    {
        string line = obj2.ReadLine();
        if (line != null && !line.Contains("Mon"))
        {   
            obj2.Close();
            TextWriter obj = File.AppendText(combined);
            obj.WriteLine("Mon\t\t\t|Thue\t\t\t|Wedn\t\t\t|Thurs\t\t\t|Friday\t\t\t|Sat\t\t\t|Sun\t\t\t    ");
            obj.Close();
        }
    }
}
Was it helpful?

Solution 2

Regardless if it's possible and what happens, just don't do it. Why? Because:

  1. it's ugly,
  2. it's against the purpose of the using statement,
  3. it's barely readable code,
  4. it's poorly maintainable,
  5. it's not undestandable by anyone else, and not even by yourself starting from tomorrow,
  6. it's an apparent code smell — an indication you hardly know what you are doing and that you are struggling with structuring your code properly.

Update: The direct consequence of points (3) and (5) above is that I misunderstood your code and thought you were assigning the new instance of TextReader into obj2. I just didn't spot there was some other variable obj with a barely different name.

OTHER TIPS

Your example is correct. You cannot, however, "reuse" obj2; that variable is readonly inside the using block. Closing and reopening the same file using a different object reference is safe; the using keyword simply guarantees that Dispose() will get called at the end of the block. On a StreamReader, Dispose() simply closes the stream, but since you've already done that inside the block, nothing will happen.

Also note that in your example, obj is not protected by using: you are not guaranteed that obj.Dispose() will be called before the block exits. This is okay, though, since you're explicitly closing the stream yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top