もう一度もう一度質問に答えます。今回は、テキストファイルの編集に関することです。これは私がこれはそれを行うための最も効率的な方法であればそれほどわからないけれども、私は、これまで持っているものである同時にテキスト入力を読み書きする効率的な方法はありますか?
Write a program that reads the contents of a text file and inserts the line numbers at the beginning of each line, then rewrites the file contents.
に従ってマイホームの仕事です。私は瞬間にテキストファイルを扱うことを学び始めました。
static void Main(string[] args)
{
string fileName = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
StreamReader reader = new StreamReader(fileName);
int lineCounter = 0;
List<string> list = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
list.Add("line " + (lineCounter + 1) + ": " + line);
line = reader.ReadLine();
lineCounter++;
}
}
StreamWriter writer = new StreamWriter(fileName);
using (writer)
{
foreach (string line in list)
{
writer.WriteLine(line);
}
}
}
ご支援いただければ幸いです!もう一度感謝します。 :]
本当にループが2回効率的だと思いますか? – Paparazzi
メモリを少なくするために 'StreamReader'を使って行うことができます。後で元のファイルが削除されている間に名前が変更されたdiffentファイルに書き込みます。 – Codor
@Codorそれは実際に素晴らしいアイデアのように聞こえる!私は別のファイルに書き込んでその名前を前のファイルの名前に変更することは考えていませんでした。入力いただきありがとうございます! – Nate