Last Updated: February 24, 2016
·
5.94K
· harrygogonis

How to open and save files in visual c++ using StreamWriter

Save Files:

if(saveFileDialog1->ShowDialog() ==                             System::Windows::Forms::DialogResult::OK)    {
    StreamWriter ^ sw = gcnew StreamWriter(saveFileDialog1->FileName);
    sw->WriteLine(myTextBox->Text);
    sw->Close();
}

Open Files (Change textBox1 to whatever form you're using):

if(openFileDialog1->ShowDialog() ==             System::Windows::Forms::DialogResult::OK)
{
    textBox1->Clear();
    StreamReader ^ sr = gcnew StreamReader(openFileDialog1->FileName);

    textBox1->Text = sr->ReadToEnd();
    this->label1->Text = openFileDialog1->FileName;
    sr->Close();
}

I recommend putting the save script inside a new function so you can call it before opening a new file.