DotNet Tutorials

Server Intellect

 Saving a Text File in WinForms using .NET 3.5 C#

This tutorial will show you one way of saving a text file from a Rich Text Box in a Windows Form. C# version.

Dealing with files in Visual Studio can be quite tricky. There are a number of ways to handle files, be it text or binary. There are a number of ways to open a file, create a file and edit a file.
In this tutorial, you will learn one way of saving text to a txt file. We will be using a Rich Text Box to input text, and then use a Menu Item to save to a txt file.

To begin, we will add a Menu Strip control to the form, and add a File > Save menu item (Just click to add), then we will also add a RichTextBox control. That's all we need. The Windows Form Designer generated code will look something like this:

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.label1 = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(284, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.saveToolStripMenuItem.Text = "Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 40);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(260, 191);
this.richTextBox1.TabIndex = 1;
this.richTextBox1.Text = "";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(11, 238);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(262, 13);
this.label1.TabIndex = 2;
this.label1.Text = "For more .NET Tutorials, visit www.dotnettutorials.com";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 264);
this.Controls.Add(this.label1);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Saving a File in .NET 3.5";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

This is the code that is generated by Visual Studio when we design our form. Yours may look different.

Once we have added our controls to the form, we can start work on the code-behind.

To add an event handler to the menu item, simply double-click it like you would a button. We will add teh following logic:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
FileInfo saveFile = new FileInfo(@"file.txt");

StreamWriter writer = saveFile.CreateText();
writer.Write(richTextBox1.Text);
writer.Close();
}

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

In the above code, we are assigning a filename ourselves. This is not practical, and we will change this shortly. The code creates a new file with the StreamWriter, and then inputs the contents of our RichTextBox. We can improve this code by letting the user choose their own filename. We can use an Input Box borrowed from Visual Basic to do this. First, right-click the References folder of your Project in Solution Explorer, then choose Add Reference. Scroll down to Microsoft.VisualBasic and add that. Once done, we can change our code to the following:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string callBox = Microsoft.VisualBasic.Interaction.InputBox("Enter filename", "Filename", "file.txt", 200, 200);

FileInfo saveFile = new FileInfo(@callBox);

StreamWriter writer = saveFile.CreateText();
writer.Write(richTextBox1.Text);
writer.Close();
}

This is much more practical, as it lets the user choose their own filename to save, which avoids overwriting. We still have problems, though. If Cancel is clicked on the InputBox, there is no filename for FileInfo to use, so it errors out. This isn't good, so we can use an IF statement and also TRY and CATCH for any other errors:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string callBox = Microsoft.VisualBasic.Interaction.InputBox("Enter filename", "Filename", "file.txt", 200, 200);

try
{
if (callBox == "")
MessageBox.Show("You must enter a filename to save");
else
{
FileInfo saveFile = new FileInfo(@callBox);

StreamWriter writer = saveFile.CreateText();
writer.Write(richTextBox1.Text);
writer.Close();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

This code is much more efficient, as it will catch any errors and notify the user. We also included the IF statement to let the user know that a filename is required.
The entire code-behind looks like this:

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 Notepad_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string callBox = Microsoft.VisualBasic.Interaction.InputBox("Enter filename", "Filename", "file.txt", 200, 200);

try
{
if (callBox == "")
MessageBox.Show("You must enter a filename to save");
else
{
FileInfo saveFile = new FileInfo(@callBox);

StreamWriter writer = saveFile.CreateText();
writer.Write(richTextBox1.Text);
writer.Close();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Looking for the VB.NET 2008 Version? Click Here!

Looking for more .NET Tutorials? Click Here!

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 
123 ASP

411 ASP

Dot Net Freaks

Server Intellect