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.
}
最初のスニペットで、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);
}
}
}
}