Search code examples
c#openfiledialogsavefiledialog

Saving TextBox content in a text file C#


I created this form that allows me to open a txt file and puts the content in a TextBox. I want to be able to modify the content writing in the textbox and then save it using the SaveFileDialog. Here's my code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1(){
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e){
            if (openFileDialog1.ShowDialog() == DialogResult.OK){
                System.IO.StreamReader input = new
                System.IO.StreamReader(openFileDialog1.FileName);
                TextBox_stampa_contenuto.AppendText(input.ReadToEnd());
                input.Close();
            }
        }

        private void salva_file_Click(object sender, EventArgs e){
            saveFileDialog1.ShowDialog();
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e){
            string name = saveFileDialog1.FileName;
            File.WriteAllText(name, TextBox_stampa_contenuto.Text);

        }
    }

}

When I run it works perfectly opening the file, but after I modify it and try to save it doesn't work. The content stays the same. There's a way to fix it? And also how can I put the text in the textbox in write mode and not in append mode. Thanks.


Solution

  • Try This:

    Solution 1: if you want to Save the contents of Textbox into TextFile you need to check the DialogResult return type of the SaveDialog.

    private void salva_file_Click(object sender, EventArgs e)
    {
            DialogResult result = saveFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string name = saveFileDialog1.FileName;
                File.WriteAllText(name, TextBox_stampa_contenuto.Text);
            }
     }
    

    Solution 2: if you want to Insert the File Text into Textbox whithout appending you need to Assign the File String into TextBox Text property.

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
      TextBox_stampa_contenuto.Text=System.IO.File.ReadAllText(openFileDialog1.FileName);      
    }