【发布时间】:2013-11-09 08:26:32
【问题描述】:
当我在 if/else 子句中实例化 Textwriter 对象时,它在子句之外是不可见的。我可以在这里做什么?我想追加或写入一个新文件。
代码如下:
private static void eventfull_doing()
{
string path, line;
int countLines;
Console.Write("Enter the name(with extension) of the file in the \"data\" folder, or create a new name(with extension): ");
path = Console.ReadLine();
TextReader inFile = new StreamReader(@"C:\data\" + path);
Console.Write("How many lines of text do you want to add to the file?: ");
countLines = Convert.ToInt32(Console.ReadLine());
if (inFile.Peek() == -1 || inFile == null)
{
TextWriter outFile = File.AppendText(@"C:\data\" + path);
}
else
{
TextWriter outFile = new StreamWriter(@"C:\data\" + path);
}
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.
}
这是我所做的:请注意,在第一个 sn-p 中,if 条件不是预期的。
string path, line;
int countLines;
Console.Write("Enter the name(with extension) of the file in the \"data\" folder, or create a new name(with extension): ");
path = Console.ReadLine();
string file = Path.Combine(@"c:\data", path);
Console.Write("How many lines of text do you want to add to the file?: ");
countLines = Convert.ToInt32(Console.ReadLine());
TextWriter outFile = null;
if (File.Exists(file))
{
using (outFile = File.AppendText(file))
{
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
}
}
else
{
using (outFile = new StreamWriter(file))
{
for (int i = 0; i < countLines; i++)
{
Console.Write("Enter line: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
}
}
}
【问题讨论】:
-
正常。在 if else 语句之外实例化它。
标签: c# object if-statement declare