Вы можете объявить это вне блоков try, просто убедитесь, что вы правильно утилизировали.
StreamWriter sw = null;
try
{
sw = new StreamWriter(File.Open("test.txt", FileMode.OpenOrCreate));
sw.Write("Some text.");
}
catch
{
// Whatever you want to catch
}
finally
{
if(sw != null)
sw.Dispose();
sw = null;
}
try
{
sw = new StreamWriter(File.Open("otherfile.txt", FileMode.OpenOrCreate));
}
catch
{
// Whatever you want to catch
}
finally
{
if(sw != null)
sw.Dispose();
sw = null;
}
Хотя я бы не советовал использовать одну и ту же переменную в нескольких пробных блоках, что вы получаете от этого?
Почему бы не что-то вроде этого:
try
{
using(var sw = new StreamWriter(File.Open("text.txt", FileMode.OpenOrCreate)))
{
sw.Write("some text");
}
}
catch
{
// handle exception
}
try
{
using(var sw = new StreamWriter(File.Open("otherfile.txt", FileMode.OpenOrCreate)))
{
sw.Write("some other text");
}
}
catch
{
// handle exception
}