6

他のデータを消去せずにテキストファイル内のテキストを新しいテキストに置き換えることは可能ですか?これが私のサンプルコードですが、機能していません。問題があることはわかっていますが、理解できません。ありがとう、

private void button1_Click_1(object sender, EventArgs e)
{
    StreamReader sr = new StreamReader("test10101.txt");
    List<string> lines = new List<string>();
    while (!sr.EndOfStream)
        lines.Add(sr.ReadLine());
    output = Convert.ToInt32(textBox1.Text);
    newbal = Convert.ToInt32(lines[0]) - output;
    MessageBox.Show("Please get your cash....\n\nYour new balance is: $" + newbal);
    sr.Close();
    {
        string linetoreplace = lines[0];
        int newlinevalue = newbal;
        string contents = sr.ReadToEnd();

        StreamWriter sw = new StreamWriter("test10101.txt" + ".tmp");
        //contents = Regex.Replace(contents, linetoreplace, newlinevalue.ToString());
        contents = contents.Replace(linetoreplace, newlinevalue.ToString());
        sw.WriteLine(contents);
        sw.Close();

    }

正規表現を使用するのか、それとも回線を直接置き換えるのか疑問に思います。

4

1 に答える 1

17

あなたはそれをもっと簡単に行うことができます:

        string[] lines = System.IO.File.ReadAllLines("test");
        lines[0] = /* replace with whatever you need */
        System.IO.File.WriteAllLines("test", lines);

お役に立てれば

int.TryParseまた、ファイルの最初の行またはテキストボックスの値が数値でない場合に備えて、コードの一部で例外を発生させたくない場合は、を使用することをお勧めします。

本当にストリームライターを使用したい場合は、これを使用することもできます。これも簡単な方法です。

line[0] = newbal.ToString();
foreach(string s in lines)
    sw.WriteLine(s);
于 2013-01-26T03:34:46.313 に答える