Conditionally open a file for output

phudgens

Member
Joined
Nov 19, 2013
Messages
19
Programming Experience
10+
I am wanting to use the following code to conditionally open a file for output based on user pereference (via checkbox on the GUI):
if (WritePerms) { StreamWriter WritePermXY = new StreamWriter(PermXYFile); }


Subsequent uses of WritePermXY such as:

if (WritePerms) WritePermXY.Write("\n"+ "EQUALS" + "\n");

generate a "'WritePermXY' does not exist in the current context" compiler error. I want to be able to open and write to a file if the user says so, but not open a file for fear of overwriting any existing file.

Does anyone think of an easy way around this?

Thanks,
Paul Hudgens
Denver



 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,138
Location
Sydney, Australia
Programming Experience
10+
You are declaring `WritePermXY` inside that `if` block so it only exists inside that `if` block. If you want to be able to use it outside that block then it must be declared outside that block, e.g.
StreamWriter writePermXY = null;

if (WritePerms)
{
    writePermXY = new StreamWriter(PermXYFile);
}

// ...

if (writePermXY != null)
{
    writePermXY.Write("\n"+ "EQUALS" + "\n");
}
 
Last edited:

phudgens

Member
Joined
Nov 19, 2013
Messages
19
Programming Experience
10+
That works great - thanks very much.

Paul Hudgens
 

phudgens

Member
Joined
Nov 19, 2013
Messages
19
Programming Experience
10+
I hadn't fully tested your previous code - you're right - it doesn't work. New code does though. Thanks.
 
Top Bottom