0

C# とクラス TextReader を使用してファイルを読み込んでいます

TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
 {
   if (someCondition)
    {
      // I want to change "line" and save it into the file I'm reading from
    }
 }

コードに質問があります: 変更された行を読み取り中のファイルに保存し、読み取りを続行するにはどうすればよいですか?

4

4 に答える 4

3

高速で汚れたソリューションは次のとおりです。

TextReader reader = new StreamReader(stream);
string line;
StringBuilder sb = new StringBuilder();
while ((line = reader.ReadLine()) != null)
{
    if (someCondition)
    {
       //Change variable line as you wish.
    }
    sb.Append(line);
 }

using (StreamWriter sw = new StreamWriter("filePath"))
{
    sw.Write(sb.ToString());
}

また

TextReader reader = new StreamReader(stream);
string line;
String newLines[];
int index = 0;
while ((line = reader.ReadLine()) != null)
{
   if (someCondition)
   {
      //Change variable line as you wish.
   }
   newLines[index] = line;
   index++;
}

using (StreamWriter sw = new StreamWriter("filePath"))
{
    foreach (string l in newLines)
    {
        sw.WriteLine(l);
    }
}

メモリが重要すぎる場合は、これも試すことができます。

TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
{
   if (someCondition)
   {
      //Change variable line as you wish.
   }
   using (StreamWriter sw = new StreamWriter("filePath"))
   {
       sw.WriteLine(line);
   }
 }
于 2012-10-13T13:31:24.047 に答える
2

最も簡単な方法は、新しいファイルを作成し、終了したら古いファイルを新しいファイルに置き換えることです。この方法では、1 つのファイルにのみ書き込みを行います。

同じファイルで読み取り/書き込みを行おうとすると、挿入するコンテンツが置き換えられるコンテンツと正確に同じサイズでない場合に問題が発生します。

テキスト ファイルに魔法はありません。それらは、テキスト エンコーディングで文字を表す単なるバイト ストリームです。ファイルには行の概念はなく、改行文字の形式のセパレーターのみです。

于 2012-10-13T13:31:51.320 に答える
2

非常に単純な解決策

void Main()
{
    var lines = File.ReadAllLines("D:\\temp\\file.txt");
    for(int x = 0; x < lines.Length; x++)
    {
        // Of course this is an example of the condtion
        // you should implement your checks
        if(lines[x].Contains("CONDITION"))
        {
            lines[x] = lines[x].Replace("CONDITION", "CONDITION2");
        }

    }
    File.WriteAllLines("D:\\temp\\file.txt", lines);
} 

欠点は、イン メモリ ラインによるメモリ使用量ですが、50MB 前後であれば、最新の PC で問題なく処理できるはずです。

于 2012-10-13T13:31:58.447 に答える
2

ファイルが大きすぎない場合は、ファイル全体を単純に書き直す必要があります。

var lines = File.ReadAllLines(path)
                .Where(l => someCondition);
File.WriteAllLines(path, lines);
于 2012-10-13T13:32:17.007 に答える