将文本写入并保存到文件c ++ visual studio中

时间:2016-03-18 16:55:25

标签: c++-cli clr

所以这里是这段代码:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 mn=textBox1->Text;
                 MessageBox::Show(mn+" "+tsk, "Info" );
                 String^ fileName = "records.txt";
                 StreamWriter^ sw = gcnew StreamWriter("records.txt");
                 sw->Write(mn,tsk);
                 sw->Close();
             }

每当我尝试从程序中将新内容写入文件时,它只会写入新文本并且不会保持旧的。我该如何保存它,所以它不会被删除?

1 个答案:

答案 0 :(得分:1)

StreamWriter constructor的文档指出,您必须将append参数设置为true,以避免仅覆盖该文件。你的代码应该是:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             mn=textBox1->Text;
             MessageBox::Show(mn+" "+tsk, "Info" );
             String^ fileName = "records.txt";
             StreamWriter^ sw = gcnew StreamWriter("records.txt", true); //append to file
             sw->Write(mn,tsk);
             sw->Close();
         }