Performing Simple File IO

Performing Simple File I/O

The .NET Framework BCL contains several types for reading and writing streams. It even contains classes specifically designed for working with files and directories. This section will demonstrate a couple of ways to work with file I/O and provide a starting place for investigating other I/O types in the BCL.

The example for this section creates a bare-bones text editor. It will enable a user to create, edit, and save text files and open existing text files. To set it up, create a new Windows Form application, add a TextBox control, set the TextBox control's Multiline property in the Object Inspector to true, and set its Dock property in the Object Inspector to Fill. Then add a MainMenu control to the Windows Form with a File menu named menuFile, add Open and Save menu items named menuFileOpen and menuFileSave, respectively, and double-click each to create stub event handlers. Next, drop OpenFileDialog and SaveFileDialog components onto the designer surface. The code in Listing 15.4 shows an easy way to implement file I/O for text files.

Listing 15.4 File I/O for Text Files (FileIO.cs)
 using System; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.IO; using System.Windows.Forms; namespace FileIO {    /// <summary>    /// Summary description for FileIO.    /// </summary>    public class FileIO : System.Windows.Forms.Form    {       /// <summary>       /// Required designer variable.       /// </summary>       private System.ComponentModel.Container components = null;       private System.Windows.Forms.TextBox textBox1;       private System.Windows.Forms.MainMenu mainMenu1;       private System.Windows.Forms.OpenFileDialog openFileDialog1;       private System.Windows.Forms.SaveFileDialog saveFileDialog1;       private System.Windows.Forms.MenuItem menuFile;       private System.Windows.Forms.MenuItem menuFileOpen;       private System.Windows.Forms.MenuItem menuFileSave;       public FileIO()       {          //          // Required for Windows Form Designer support          //          InitializeComponent();          //          // TODO: Add any constructor code after InitializeComponent call          //       }       /// <summary>       /// Clean up any resources being used.       /// </summary>       protected override void Dispose (bool disposing)       {          if (disposing)          {             if (components != null)             {                components.Dispose();             }          }          base.Dispose(disposing);       }       #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.textBox1 = new System.Windows.Forms.TextBox();          this.mainMenu1 = new System.Windows.Forms.MainMenu();          this.menuFile = new System.Windows.Forms.MenuItem();          this.menuFileOpen = new System.Windows.Forms.MenuItem();          this.menuFileSave = new System.Windows.Forms.MenuItem();          this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();          this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();          this.SuspendLayout();          //          // textBox1          //          this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;          this.textBox1.Location = new System.Drawing.Point(0, 0);          this.textBox1.Multiline = true;          this.textBox1.Name = "textBox1";          this.textBox1.Size = new System.Drawing.Size(292, 266);          this.textBox1.TabIndex = 0;          this.textBox1.Text = "textBox1";          //          // mainMenu1          //          this.mainMenu1.MenuItems.AddRange(             new System.Windows.Forms.MenuItem[] {          this.menuFile});          //          // menuFile          //          this.menuFile.Index = 0;          this.menuFile.MenuItems.AddRange(             new System.Windows.Forms.MenuItem[] {          this.menuFileOpen,          this.menuFileSave});          this.menuFile.Text = "&File";          //          // menuFileOpen          //          this.menuFileOpen.Index = 0;          this.menuFileOpen.Text = "&Open";          this.menuFileOpen.Click +=             new System.EventHandler(this.menuFileOpen_Click);          //          // menuFileSave          //          this.menuFileSave.Index = 1;          this.menuFileSave.Text = "&Save";          this.menuFileSave.Click +=             new System.EventHandler(this.menuFileSave_Click);          //          // FileIO          //          this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);          this.ClientSize = new System.Drawing.Size(292, 266);          this.Controls.Add(this.textBox1);          this.Menu = this.mainMenu1;          this.Name = "FileIO";          this.Text = "FileIO";          this.ResumeLayout(false);       }       #endregion       /// <summary>       /// The main entry point for the application.       /// </summary>       [STAThread]       static void Main()       {          Application.Run(new FileIO());       }       private void menuFileOpen_Click(object sender, System.EventArgs e)       {          DialogResult dlgRes = openFileDialog1.ShowDialog();          if (dlgRes == DialogResult.OK)          {             using (StreamReader sr =                File.OpenText(openFileDialog1.FileName))             {                textBox1.Text = sr.ReadToEnd();             }          }       }       private void menuFileSave_Click(object sender, System.EventArgs e)       {          DialogResult dlgRes = saveFileDialog1.ShowDialog();          if (dlgRes == DialogResult.OK)          {             using (StreamWriter sw =                File.CreateText(saveFileDialog1.FileName))             {                sw.Write(textBox1.Text);             }          }       }    } } 

The code in Listing 15.4 uses the Click event handlers of the Open and Save menu items to, respectively, open and save the contents of the TextBox control. They also use the OpenFileDialog and SaveFileDialog common dialogs for graphical interaction with the user.

The interesting parts of each event handler are within the using statements. The open event handler uses the static OpenText method of the File class for opening a text file. The File class has other static methods for opening files in different ways, but this one was the simplest for our purposes. When the file is opened, the OpenText method returns a StreamReader object, which is specially made for reading text files. Within the using statement, a simple call to ReadToEnd reads the entire contents of the file and puts the string retrieved into the TextBox control. Because the file was opened in a using statement, the Close method will be called automatically when control leaves the using statement block. Had the using statement not been used, it would have been proper to open the file in a try block and close it in a finally block.

The save event handler works very much the same way as the open, except it uses different objects and saves the file. This logic uses the Write method of the StreamWriter to persist the entire contents of the TextBox control.

Remember to add a using declaration at the top of the file for the System.IO namespace. Otherwise, all file and stream objects would need to be qualified with System.IO, for example, System.IO.File.OpenText(...). The System.IO namespace contains many predefined types to meet most file I/O and stream needs. A similar type to the File class is Directory, which also has static methods for working with file system directories. There are also the FileInfo and DirectoryInfo classes, which permit creating instances to perform many of the same functions as the File and Directory types.



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net