Microsoft KB Archive/910356

= How to perform the basic file I/O operations in Visual C# 2005 Express Edition =

Article ID: 910356

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual Studio 2005 Standard Edition
 * Microsoft Visual Studio 2005 Professional Edition
 * Microsoft Visual Studio 2005 Express Edition
 * Microsoft Visual C# 2005 Express Edition
 * Microsoft Visual Studio 2005 Team System Architect Edition
 * Microsoft Visual Studio 2005 Team System Developer Edition
 * Microsoft Visual Studio 2005 Team Foundation
 * Microsoft Visual Studio 2005 Team System Test Edition

-







For a Microsoft Visual Basic .NET version of this article, see 304427.



For a Microsoft Visual C++ .NET version of this article, see 307398.



For a Microsoft Visual C# .NET version of this article, see 304430.

This article refers to the System.IO Microsoft .NET Framework Class Library namespace.



INTRODUCTION
This step-by-step article describes how to perform the basic file I/O operations in Microsoft Visual C# 2005 Express Edition. If you are new to the Microsoft .NET Framework, you will find that the object model for the file operations in Microsoft .NET is similar to the FileSystemObject object model that is popular with many Microsoft Visual Studio 6.0 developers. To make the transition easier, the functionality that is described in this article is based on the following Microsoft Knowledge Base article:

186118 How to use FileSystemObject with Visual Basic

You can still use the FileSystemObject object in .NET. Because the FileSystemObject object is a Component Object Model (COM) component, .NET requires that you access the FileSystemObject object through the interop layer. If you want to use a wrapper, .NET generates a wrapper for the component for you. However, the following classes in the .NET Framework offer functionality that is unavailable when you use the FileSystemObject object, without the overhead of the interop layer:
 * The File class
 * The FileInfo class
 * The Directory class
 * The DirectoryInfo class
 * Other related classes

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual C# 2005 Express Edition or Microsoft Visual Studio 2005

Demonstrated file I/O operations
The code examples in this article describe how to perform the basic file I/O operations. The &quot;Step-by-step example&quot; section describes how to create a sample program that demonstrates the following file I/O operations:
 * Read a text file.
 * Write a text file.
 * View file information.
 * List disk drives.
 * List folders.
 * List files.

Note If you want to use the following code examples directly, consider the following:   You must include the System.IO namespace as follows. using System.IO;   You must declare the winDir variable as follows. string   winDir=System.Environment.GetEnvironmentVariable(&quot;windir&quot;);   You must declare the addListItem function as follows. private void addListItem(string value) {   this.listbox1.Items.Add(value); } Note Instead of declaring and using the addListItem function, you can use the following statement directly. this.listbox1.Items.Add(value); 

Read a text file
The following code example uses a StreamReader class to read the System.ini file. The contents of the file are added to a ListBox control. The try...catch block is used to notify the application if the file is empty. There are many ways to determine when the end of the file is reached. This code example uses the Peek method to examine the next line before reading it. StreamReader reader = new StreamReader(winDir + &quot;\\system.ini&quot;); try {               do                { addListItem(reader.ReadLine); }               while (reader.Peek != -1); }

catch {               addListItem(&quot;File is empty.&quot;); }

finally {               reader.Close; }

Write a text file
The following code example uses a StreamWriter class to create a file and to write to a file. If you have an existing file, you can open the existing file in the same way. StreamWriter writer = new StreamWriter(&quot;c:\\KBTest.txt&quot;); writer.WriteLine(&quot;File created by using StreamWriter class.&quot;); writer.Close; this.listBox1.Items.Clear; addListItem(&quot;File written to C:\\KBTest.txt&quot;);

View file information
The following code example uses a FileInfo object to access a file's properties. The Notepad.exe file is used in this code example. The properties appear in a ListBox control. FileInfo FileProps = new FileInfo(winDir + &quot;\\notepad.exe&quot;); addListItem(&quot;File Name = &quot; + FileProps.FullName); addListItem(&quot;Creation Time = &quot; + FileProps.CreationTime); addListItem(&quot;Last Access Time = &quot; + FileProps.LastAccessTime); addListItem(&quot;Last Write Time = &quot; + FileProps.LastWriteTime); addListItem(&quot;Size = &quot; + FileProps.Length); FileProps = null;

List disk drives
The following code example uses the Directory class and the Drive class to retrieve a list of the logical drives on a system. For this code example, the results appear in a ListBox control. string[] drives = Directory.GetLogicalDrives; foreach(string drive in drives) {       addListItem(drive); }

List folders
The following code example uses the GetDirectories method of the Directory class to retrieve a list of folders. string[] dirs = Directory.GetDirectories(winDir); foreach(string dir in dirs) {           addListItem(dir); }

List files
The following code example uses the GetFiles method of the Directory class to retrieve a list of files. string[] files = Directory.GetFiles(winDir); foreach (string fileName in files) {               addListItem(fileName); } Various problems may occur when users try to access files. The files may not exist, or the files may be being used. Also, users may not have permissions on the files or the folders that they are trying to access. You must consider these possibilities when you write code and make provisions to handle the exceptions that may be generated.

Step-by-step example
To create a sample program that demonstrates the basic file I/O operations, follow these steps:  In Visual C# 2005 Express Edition or in Visual Studio 2005, create a new Visual C# Windows application that is named WindowsApplication1. By default, a form that is named Form1 is created.</li> In Solution Explorer, right-click Form1.cs, and then click View Code.</li> Delete all the code in the Code Editor.</li>  Paste the following code into the Code Editor. using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;

namespace WindowsApplication1 {   public partial class Form1 : Form {       public Form1 {           InitializeComponent; }

private void Form1_Load(object sender, EventArgs e)       { this.button1.Text = &quot;Read Text File&quot;; this.button2.Text = &quot;Write Text File&quot;; this.button3.Text = &quot;View File Information&quot;; this.button4.Text = &quot;List Drives&quot;; this.button5.Text = &quot;List Subfolders&quot;; this.button6.Text = &quot;List Files&quot;; }

private void button1_Click(object sender, EventArgs e)       { // How to read a text file. // try...catch is to deal with a file that has a length of 0 bytes. this.listBox1.Items.Clear; StreamReader reader = new StreamReader(winDir + &quot;\\system.ini&quot;); try {               do                { addListItem(reader.ReadLine); }               while (reader.Peek != -1); }

catch {               addListItem(&quot;File is empty.&quot;); }

finally {               reader.Close; }       }

private void button2_Click(object sender, EventArgs e)       { // How to create and write to a text file. StreamWriter writer = new StreamWriter(&quot;c:\\KBTest.txt&quot;); writer.WriteLine(&quot;File created by using StreamWriter class.&quot;); writer.Close; this.listBox1.Items.Clear; addListItem(&quot;File written to C:\\KBTest.txt&quot;); }

private void button3_Click(object sender, EventArgs e)       { // How to retrieve file properties (example uses Notepad.exe). this.listBox1.Items.Clear; FileInfo FileProps = new FileInfo(winDir + &quot;\\notepad.exe&quot;); addListItem(&quot;File Name = &quot; + FileProps.FullName); addListItem(&quot;Creation Time = &quot; + FileProps.CreationTime); addListItem(&quot;Last Access Time = &quot; + FileProps.LastAccessTime); addListItem(&quot;Last Write Time = &quot; + FileProps.LastWriteTime); addListItem(&quot;Size = &quot; + FileProps.Length); FileProps = null; }

private void button4_Click(object sender, EventArgs e)       { // How to obtain a list of disk drives. this.listBox1.Items.Clear; string[] drives = Directory.GetLogicalDrives; foreach (string drive in drives) {               addListItem(drive); }       }

private void button5_Click(object sender, EventArgs e)       { // How to obtain a list of folders. // Example uses Windows folder. this.listBox1.Items.Clear; string[] dirs = Directory.GetDirectories(winDir); foreach (string dir in dirs) {               addListItem(dir); }       }

private void button6_Click(object sender, EventArgs e)       { // How to obtain a list of files. // Example uses Windows folder. this.listBox1.Items.Clear; string[] files = Directory.GetFiles(winDir); foreach (string fileName in files) {               addListItem(fileName); }       }    } } </li> In Solution Explorer, right-click Form1.Designer.cs, and then click View Code.</li> Delete all the code in the Code Editor.</li>  Paste the following code into the Code Editor. namespace WindowsApplication1 {   partial class Form1 {       ///         /// Required designer variable. ///        private System.ComponentModel.IContainer components = null;

private string winDir = System.Environment.GetEnvironmentVariable(&quot;windir&quot;);

///        /// Clean up any resources that are being used. ///        /// <param name=&quot;disposing&quot;>true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) {           if (disposing && (components != null)) {               components.Dispose; }           base.Dispose(disposing); }

private void addListItem(string value) {           this.listBox1.Items.Add(value); }

#region Windows Form Designer generated code

///        /// Required method for designer support - do not modify /// the contents of this method with the code editor. ///        private void InitializeComponent {           this.listBox1 = new System.Windows.Forms.ListBox; this.button1 = new System.Windows.Forms.Button; this.button2 = new System.Windows.Forms.Button; this.button3 = new System.Windows.Forms.Button; this.button4 = new System.Windows.Forms.Button; this.button5 = new System.Windows.Forms.Button; this.button6 = new System.Windows.Forms.Button; this.SuspendLayout; //            // listBox1 //            this.listBox1.FormattingEnabled = true; this.listBox1.Location = new System.Drawing.Point(23, 24); this.listBox1.Name = &quot;listBox1&quot;; this.listBox1.Size = new System.Drawing.Size(525, 251); this.listBox1.TabIndex = 0; //            // button1 //            this.button1.Location = new System.Drawing.Point(23, 290); this.button1.Name = &quot;button1&quot;; this.button1.Size = new System.Drawing.Size(171, 23); this.button1.TabIndex = 1; this.button1.Text = &quot;button1&quot;; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); //            // button2 //            this.button2.Location = new System.Drawing.Point(23, 319); this.button2.Name = &quot;button2&quot;; this.button2.Size = new System.Drawing.Size(171, 23); this.button2.TabIndex = 2; this.button2.Text = &quot;button2&quot;; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); //            // button3 //            this.button3.Location = new System.Drawing.Point(200, 290); this.button3.Name = &quot;button3&quot;; this.button3.Size = new System.Drawing.Size(171, 23); this.button3.TabIndex = 3; this.button3.Text = &quot;button3&quot;; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); //            // button4 //            this.button4.Location = new System.Drawing.Point(200, 319); this.button4.Name = &quot;button4&quot;; this.button4.Size = new System.Drawing.Size(171, 23); this.button4.TabIndex = 4; this.button4.Text = &quot;button4&quot;; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); //            // button5 //            this.button5.Location = new System.Drawing.Point(377, 290); this.button5.Name = &quot;button5&quot;; this.button5.Size = new System.Drawing.Size(171, 23); this.button5.TabIndex = 5; this.button5.Text = &quot;button5&quot;; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); //            // button6 //            this.button6.Location = new System.Drawing.Point(377, 319); this.button6.Name = &quot;button6&quot;; this.button6.Size = new System.Drawing.Size(171, 23); this.button6.TabIndex = 6; this.button6.Text = &quot;button6&quot;; this.button6.UseVisualStyleBackColor = true; this.button6.Click += new System.EventHandler(this.button6_Click); //            // Form1 //            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(580, 400); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.listBox1); this.Name = &quot;Form1&quot;; this.Text = &quot;Form1&quot;; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; } } </li> Press F5 to build and run the application.</li> Click the buttons to view the different actions.</li></ol>

Note By default, Visual C# 2005 Express Edition or Visual Studio 2005 adds one form to the project when you create a Windows Forms project. The form is named Form1. The two files that represent the form are named the Form1.cs file and the Form1.designer.cs file. You write the code in the Form1.cs file. The Windows Forms Designer writes the code in the Form1.designer.cs file.

For more information about the Windows Forms Designer in Visual C# 2005 Express Edition or in Visual Studio 2005, visit the following Microsoft Developer Network (MSDN) Web site:

http://msdn2.microsoft.com/en-us/library/ms173077.aspx

Additional query words: Visual C# 2005 Express File IO Streaming I/O Sample Code Visual Studio 2005 System.IO

Keywords: kbvs2005std kbvs2005mos kbvs2005exp kbvs2005pro kbvs2005search kbio kbhowtomaster kbsample kbstepbystep kbcodesnippet kbcode kbhowto KB910356

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.