ファイル全体を書き換えずに行を書き換えることはできません (行がたまたま同じ長さでない限り)。ファイルが小さい場合は、ターゲット ファイル全体をメモリに読み込んでから、再度書き出すことが理にかなっています。次のようにできます。
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);
// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}
ファイルが大きい場合は、新しいファイルを作成して、一方のファイルからストリーミングを読み込んで、もう一方のファイルに書き込めるようにすることをお勧めします。これは、一度にファイル全体をメモリに保持する必要がないことを意味します。次のようにできます。
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";
// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}
if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);
// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}
// TODO: Delete the old file and replace it with the new file here.
}
}
書き込み操作が成功したことを確認したら、後でファイルを移動できます (例外がスローされず、ライターが閉じられます)。
どちらの場合も、行番号に 1 ベースのインデックスを使用しているため、少し混乱することに注意してください。コードで 0 ベースのインデックスを使用する方が理にかなっている場合があります。必要に応じて、プログラムへのユーザー インターフェイスで 1 から始まるインデックスを使用できますが、さらに送信する前に 0 から始まるインデックスに変換してください。
また、古いファイルを新しいファイルで直接上書きすることの欠点は、途中で失敗すると、書き込まれていないデータが永久に失われる可能性があることです。最初に 3 番目のファイルに書き込むことにより、元のデータの別の (修正された) コピーがあることを確認した後にのみ元のデータを削除するので、コンピューターが途中でクラッシュした場合にデータを復元できます。
最後のコメント: あなたのファイルの拡張子は xml であることに気付きました。特定の行を置き換えるのではなく、XML パーサーを使用してファイルの内容を変更する方が合理的かどうかを検討することをお勧めします。