Jump to content

Creating & Writing to a Text File in Windows Forms Application

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Oran

Oran

    Newbie

  • Members
  • Pip
  • 5 posts
Hello,
I've been trying to save a text from a textbox to a file in a specified folder, but all the guides I found in the Internet refer to a Console Application.
So basically I'm asking how to:
1. Create a *.txt File in a specified directory, for instance the desktop.
2. Write text to the file
3. Have it all done in a Windows Forms Application
Thanks for any help

#2
wraith

wraith

    Newbie

  • Members
  • Pip
  • 5 posts
Create a Method like...

WriteToFile(text)
{
using (System.IO.StreamWriter sw = File.AppendText(FILE)) // FILE is the full path to the file - C:\\test.txt for example
{
sw.WriteLine(text);
sw.Close();
}
}

Make a button which calls this method on click with the textbox.Text as parameter and you're done :)

#3
Diastro

Diastro

    Newbie

  • Members
  • Pip
  • 2 posts
Hey!

Here's an other method you could use, using a Rich Text Box.

That's what the form looks like :

Posted Image

And for the 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;



namespace Text_Writer

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();


        }


        private void button1_Click(object sender, EventArgs e)

        {

            richTextBox1.SaveFile(textBox1.Text, RichTextBoxStreamType.PlainText);

        }

    }

}


Hope this will Help

David




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users