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



 
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:
Back
Top Bottom