1

TXTファイルからデータを読み取っていますが、既存のデータの一部を置き換えてから、ファイルに書き戻す必要があります。問題は、ファイルにテキストを書き戻すときに破損する特殊文字がファイルにあることです。

たとえば、ファイル「foo.txt」に次の「€rdrf+À[HIGH]」という文字列があります。私のアプリケーションは、テキストを文字列に読み込み、その行を調べて[HIGH]を値に置き換えてから、ファイルに書き戻します。問題は、特殊なテキスト文字が破損することです。

コードベースの短縮バージョンは次のとおりです。

string fileText = System.IO.File.ReadAllText("foo.txt");
fileText= iPhoneReferenceText.Replace("[HIGH]", low);
TextWriter tw = new StreamWriter("Path");
tw.WriteLine(fileText);
tw.Close(); 

特殊なテキスト文字を破損せずにファイルから読み取るにはどうすればよいですか?

ありがとうジェイ

4

2 に答える 2

1

適切なエンコーディングが必要だと思います

string fileText = System.IO.File.ReadAllText("foo.txt", Encoding.XXXX);
.
.
tw = new StreamWriter("path", Encoding.XXXX);
.
.

XXXX は次のいずれかです。

  System.Text.ASCIIEncoding
  System.Text.UnicodeEncoding
  System.Text.UTF7Encoding
  System.Text.UTF8Encoding
于 2010-10-08T21:47:26.340 に答える
0

これを試して :

        string filePath = "your file path";
        StreamReader reader = new StreamReader(filePath);
        string text = reader.ReadToEnd();
        // now you edit your text as you want
        string updatedText = text.Replace("[HIGH]", "[LOW]");

        reader.Dispose(); //remember to dispose the reader so you can overwrite on the same file
        StreamWriter writer = new StreamWriter(filePath);
        writer.Write(text, 0, text.Length);
        writer.Dispose(); //dispose the writer
        Console.ReadLine();

読み手、書き手共に終了後は必ず廃棄してください。

于 2012-03-04T21:32:09.407 に答える