JonnyAppleseed
JonnyAppleseed

Reputation: 51

Unable to automatically save a file after reading it in. c#

I am attempting to create a note taking application (first Windows Forms application). So far I have managed to read a .txt file into a RichTextBox. I am trying to make the program create and save the .txt file containing the contents of the .txt file that was read in read in. So when the user adds text from a file it creates a new file in a notes folders that is in the root directory of application. Please see my code below. Any advice would be greatly appreciated. Cheers

private void button1_Click(object sender, EventArgs e)
    {
        //read in a .txt file
        OpenFileDialog op = new OpenFileDialog();
        if (op.ShowDialog() == DialogResult.OK) 
        richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
        this.Text = op.FileName;

        string fileName = op.FileName;

        //create new .txt file contaning module notes
        System.IO.StreamWriter file = new System.IO.StreamWriter("\\"+fileName);
        file.WriteLine(fileName);
        file.Close();
    }

Upvotes: 0

Views: 63

Answers (2)

Nikki9696
Nikki9696

Reputation: 6348

Tested and working

 //read in a .txt file
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
                richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
            this.Text = op.FileName;

            string fileName = Path.Combine(Application.CommonAppDataPath, Path.GetFileName(op.FileName));
            File.WriteAllText(fileName, "test");

Upvotes: 1

Nathan
Nathan

Reputation: 6216

  • wrap your streams, files (anything that implements IDisposable) in a using block:

using(var myfile = File. CreateText(path) ) { myfile.WriteLine("hi"); }

  • it's not creating a file because the path is wrong

Upvotes: 0

Related Questions