1

streamreader と streamwriter を使用するプロジェクトを作成しています。他の行に影響を与えることなく、特定の行のテキストのみを置換または保存することは可能ですか? 私がこのように作れば

streamreader sr = new streamreader(@"txtfile");
list<string> lines = new list<string>();
while (!sr.EndOfStream)
sr.readline();
{
     lines.Add(sr.ReadLine();
}

//put in textbox
sr.close();

{
streamwriter sw = new streamwriter(@"txtfile");
sw.WriteLine(textBox1.text);
sw.close();
}

これは単なるサンプルですが、ストリームライターでもリストを使用することは可能ですか?

4

3 に答える 3

1

1行のソリューションが必要な場合(コードゴルフ:))使用できます

string path = @"C:\Test.txt";
string lineToReplace = "Relpace This Line";
string newLineValue = "I Replaced This Line";

File.WriteAllLines(path, File.ReadAllLines(path).Select(line => line.Equals(lineToReplace) ? newLineValue : line));
于 2013-01-24T04:54:36.083 に答える
0

行をそのまま変更することはできませんが、ReadAllLinesを実行して、変更したい行を見つけて変更し、すべてをファイルに再度書き込むことができます

StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(@"txtfile");

foreach (string line in file)
{
    if (line.Contains("string you want to replace"))
    {
        temp = line.Replace("string you want to replace", "New String");
        newFile.Append(temp + "\r\n");
        continue;
    }
    newFile.Append(line + "\r\n");
}

File.WriteAllText(@"txtfile", newFile.ToString());
于 2013-01-24T04:48:02.600 に答える
0

ファイルをメモリに読み込み、変更したい行を変更し、リーダーを閉じ、ファイルを書き込み用に開き、ファイルの新しい内容を書き出します。

于 2013-01-24T04:26:04.613 に答える