You can declare it before the if
statement, but with no assignment - and then make sure that you assign a value to it in both branches:
TextWriter outFile;
if (inFile.Peek() == -1 || inFile == null)
{
outFile = File.AppendText(@"C:\data\" + path);
}
else
{
outFile = new StreamWriter(@"C:\data\" + path);
}
However, the fact that you still have the file open if it exists may well cause you problems - and it's not clear why you're calling File.AppendText
if you've found that it's empty anyway. Are you actually just trying to create or append? If so, just use AppendText
- it'll be fine.
You should also use a using
statement to close the writer automatically... and if you do need to use @"C:\data\" + path
in several places, I'd extract that common expression to a local variable:
string file = Path.Combine(@"c:\data", path);
// Now use file everywhere
If you do stick to using File.AppendText
or the StreamWriter
constructor, consider using a conditional expression:
TextWriter outFile = inFile.Peek() == -1 || inFile == null
? File.AppendText(file) : new StreamWriter(file);