c# 如何修改txt文件中的内容

2024-12-29 13:16:09
推荐回答(4个)
回答1:

既然你可以读出来,写进去应该问题不大吧。根据msgs找到txt中对应的文本,然后替换掉第二个冒号后面的内容,把新的内容重新写入txt文档。

回答2:

using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\" + "LOGIN_.txt"))
{
sw.WriteLine("LOGIN_Tom:79:"+this.textBox1.Text);
sw.Close();
}

回答3:

string ppath = Application.StartupPath + "\\" + "LOGIN_.txt";
StreamReader srlogin = new StreamReader(ppath);
string msgs = srlogin.ReadToEnd();
string msgHead = msgs.Substring(0, 6);
string msgContent = msgs.Substring(6);
string[] info = msgContent.Split(':');
msgs = msgs.Replace(info[2], this.textBox1.Text);
srlogin.Close();
File.WriteAllText(ppath, msgs);
MessageBox.Show("Done");

回答4:

请参考一下代码

       private void button1_Click(object sender, EventArgs e)

        {

            var reads= File.ReadAllBytes("test.txt");

            richTextBox1.Text = Encoding.Default.GetString(reads).Remove(0,6);

            MessageBox.Show("读取成功!!"); 

        }


        private void button2_Click(object sender, EventArgs e)

        {

            var writes = Encoding.Default.GetBytes("LOGIN_Tom:79:"+richTextBox1.Text);

            File.WriteAllBytes("test.txt",writes);

            MessageBox.Show("成功写入!!");

        }