Microsoft KB Archive/323168

= HOW TO: Do Basic File I/O in Visual J# .NET =

Article ID: 323168

Article Last Modified on 8/7/2003

-

APPLIES TO


 * Microsoft Visual J# .NET 2003 Standard Edition
 * Microsoft Visual J# .NET 2003 Standard Edition

-



This article was previously published under Q323168



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

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

IN THIS TASK
SUMMARY Requirements Discussion of Demonstrated File I/O Operations
 * Read a Text File
 * Write a Text File
 * View File Information
 * List Disk Drives
 * List Subfolders
 * List Files

Step-by-Step Example



SUMMARY
The step-by-step procedure that is outlined in this article demonstrates how to do six basic file input/output (I/O) operations in Visual J# .NET. If you are new to Microsoft .NET, you will find that the object model for file operations in .NET is similar to the FileSystemObject (FSO) that was popular with many Visual Studio 6.0 developers. To make the transition easier, the functionality that is demonstrated in this article is based on the following Microsoft Knowledge Base article:

186118 HOWTO: Use FileSystemObject with Visual Basic

It is still possible to use the FileSystemObject in .NET. Because the FileSystemObject is a Component Object Model (COM) component, .NET requires that access to the object be through the Interop layer. .NET generates a wrapper for the component for you, if you choose to use it. However, the File class, the FileInfo class, the Directory class, the DirectoryInfo class, and other related classes in the .NET Framework offer functionality that is not available with the FSO, without the overhead of the Interop layer.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
 * Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
 * Microsoft Visual Studio .NET
 * Microsoft Visual Studio .NET Software Development Kit (SDK) Quickstarts
 * Microsoft Visual J# .NET Beta 2

back to the top

Discussion of Demonstrated File I/O Operations
The examples in this article describe basic file I/O operations. The &quot;Step-by-Step Example&quot; section describes how to create a sample application that demonstrates the following six file I/O operations:


 * Read a Text File
 * Write a Text File
 * View File Information
 * List Disk Drives
 * List SubFolders
 * List Files

NOTE: If you want to use the following code samples directly, be aware of the following:   You must include the System namespace and the System.IO namespace, as follows: import System.*; import System.IO.*;   Declare the winDir variable as follows: System.String winDir = System.Environment.GetEnvironmentVariable(&quot;windir&quot;);   The addListItem function is declared as follows: private void addListItem(System.String value) {  listBox1.get_Items.Add (value); } NOTE: Instead of declaring and using the addListItem function, you can use the following statement directly: listBox1.get_Items.Add (value); 

back to the top

Read a Text File
The following code sample 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 alert the program if the file is empty. There are a number of ways to determine when the end of the file is reached; this sample uses the Peek method to examine the next line before reading it. // Connect to read file. System.IO.StreamReader reader = new System.IO.StreamReader(winDir + &quot;\\system.ini&quot;); // Clear box. listBox1.get_Items.Clear;

// Build list. try {                do                  { addListItem(reader.ReadLine); }                while(reader.Peek != -1); }

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

finally {                reader.Close; } back to the top

Write a Text File
This code sample uses a StreamWriter class to create and write to a file. If you have an existing file, you can open it in the same way. // Create or connect to write file. System.IO.StreamWriter writer = new System.IO.StreamWriter(&quot;c:\\KBTest.txt&quot;);

// Write to file. writer.WriteLine(&quot;File created using the StreamWriter class&quot;); writer.Close; listBox1.get_Items.Clear; addListItem(&quot;File written to C:\\KBTest.txt&quot;); back to the top

View File Information
This code sample uses a FileInfo object to access the properties of a file. Notepad.exe is used in this sample. The properties are displayed in a ListBox control. System.IO.FileInfo fileProps = new System.IO.FileInfo(winDir + &quot;\\notepad.exe&quot;); listBox1.get_Items.Clear; addListItem (&quot;File Name = &quot; + fileProps.get_FullName); addListItem (&quot;Creation Time = &quot; + fileProps.get_CreationTime); addListItem (&quot;Last Access Time = &quot; + fileProps.get_LastAccessTime); addListItem (&quot;Last Write Time = &quot; + fileProps.get_LastWriteTime); addListItem (&quot;Size = &quot; + fileProps.get_Length); fileProps = null; back to the top

List Disk Drives
This code sample uses the Directory and Drive classes to list the logical drives on a system. For the sample, the results are displayed in a ListBox control. int loop, size; System.String[] drive = System.IO.Directory.GetLogicalDrives; size = drive.length; listBox1.get_Items.Clear; for (loop = 0; loop < size; loop ++) addListItem(drive[loop].ToString); back to the top

List Subfolders
This code sample uses the GetDirectories method of the Directory class to get a list of folders. int loop, size; System.String[] dir = System.IO.Directory.GetDirectories(winDir); size = dir.length; listBox1.get_Items.Clear; for (loop = 0; loop < size; loop ++) addListItem(dir[loop].ToString ); back to the top

List Files
This code sample uses the GetFiles method of the Directory class to get a listing of files. int loop, size; listBox1.get_Items.Clear; System.String[] file = System.IO.Directory.GetFiles(winDir); size = file.length; for (loop = 0; loop < size; loop ++) addListItem(file[loop].ToString); Many things can go wrong when a user accesses files. The files may not exist, the files may be in use, or users may not have permissions on the files of folders that they are trying to access. It is important to consider these possibilities when you write code and to handle the exceptions that may be generated.

back to the top

Step-by-Step Example
 In Visual J# .NET, start a new Windows application. By default, Form1 is created. Name the new Windows application TestIO. Right-click Form1, and then click View Code.</li> Delete all of the code in the Code-Behind Editor.</li>  Paste the following code in the Code-Behind Editor window: package TestIO;

import System.Drawing.*; import System.Collections.*; import System.ComponentModel.*; import System.Windows.Forms.*; import System.Data.*;

/** * Summary description for Form1. */ public class Form1 extends System.Windows.Forms.Form {

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; private System.Windows.Forms.ListBox listBox1; /**      * Required designer variable. */      private System.ComponentModel.Container components = null;

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

public Form1 {           //             // Required for Windows Form Designer support. //            InitializeComponent; }

/**      * Clean up any resources being used. */      protected void Dispose(boolean disposing) {           if (disposing) {                 if (components != null) {                       components.Dispose; }           }            super.Dispose(disposing); }

#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.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.listBox1 = new System.Windows.Forms.ListBox; this.SuspendLayout;

//            // button1 //            this.button1.set_Location(new System.Drawing.Point(528, 16)); this.button1.set_Name(&quot;button1&quot;); this.button1.set_Size(new System.Drawing.Size(120, 56)); this.button1.set_TabIndex(0); this.button1.set_Text(&quot;Read Text File&quot;); this.button1.add_Click ( new System.EventHandler(this.button1_Click) );

//            // button2 //            this.button2.set_Location(new System.Drawing.Point(528, 88)); this.button2.set_Name(&quot;button2&quot;); this.button2.set_Size(new System.Drawing.Size(120, 56)); this.button2.set_TabIndex(1); this.button2.set_Text(&quot;Write Text File&quot;); this.button2.add_Click ( new System.EventHandler(this.button2_Click) );

//            // button3 //            this.button3.set_Location(new System.Drawing.Point(528, 160)); this.button3.set_Name(&quot;button3&quot;); this.button3.set_Size(new System.Drawing.Size(120, 56)); this.button3.set_TabIndex(2); this.button3.set_Text(&quot;View File Information&quot;); this.button3.add_Click ( new System.EventHandler(this.button3_Click) );

//            // button4 //            this.button4.set_Location(new System.Drawing.Point(528, 232)); this.button4.set_Name(&quot;button4&quot;); this.button4.set_Size(new System.Drawing.Size(120, 56)); this.button4.set_TabIndex(3); this.button4.set_Text(&quot;List Drives&quot;); this.button4.add_Click ( new System.EventHandler(this.button4_Click) );

//            // button5 //            this.button5.set_Location(new System.Drawing.Point(528, 304)); this.button5.set_Name(&quot;button5&quot;); this.button5.set_Size(new System.Drawing.Size(120, 56)); this.button5.set_TabIndex(4); this.button5.set_Text(&quot;List Subfolders&quot;); this.button5.add_Click ( new System.EventHandler(this.button5_Click) );

//            // button6 //            this.button6.set_Location(new System.Drawing.Point(528, 376)); this.button6.set_Name(&quot;button6&quot;); this.button6.set_Size(new System.Drawing.Size(120, 56)); this.button6.set_TabIndex(5); this.button6.set_Text(&quot;List Files&quot;); this.button6.add_Click ( new System.EventHandler(this.button6_Click) );

//            // listBox1 //            this.listBox1.set_Location(new System.Drawing.Point(16, 16)); this.listBox1.set_Name(&quot;listBox1&quot;); this.listBox1.set_Size(new System.Drawing.Size(496, 459)); this.listBox1.set_TabIndex(6);

//            // Form1 //            this.set_AutoScaleBaseSize(new System.Drawing.Size(5, 13)); this.set_ClientSize(new System.Drawing.Size(672, 493)); this.get_Controls.AddRange(new System.Windows.Forms.Control[]                  {                        this.listBox1,                                      this.button6,                                      this.button5,                                      this.button4,                                      this.button3,                                      this.button2,                                      this.button1}); this.set_Name(&quot;Form1&quot;); this.set_Text(&quot;Form1&quot;); this.ResumeLayout(false);

}

#endregion

/** @attribute System.STAThread */ public static void main(String[] args) {Application.Run(new Form1);}

// Add to list box. private void addListItem (System.String value) {listBox1.get_Items.Add(value);}

// Read text file. private void button1_Click (System.Object sender, System.EventArgs e)     { System.IO.StreamReader reader = new System.IO.StreamReader(winDir + &quot;\\system.ini&quot;); listBox1.get_Items.Clear; try {                do                 { addListItem(reader.ReadLine); }                while(reader.Peek  != -1); }

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

finally {                reader.Close ; }     }

// Create and write a text file. private void button2_Click (System.Object sender, System.EventArgs e)     { System.IO.StreamWriter writer = new System.IO.StreamWriter(&quot;c:\\KBTest.txt&quot;); writer.WriteLine(&quot;File created using the StreamWriter class&quot;); writer.Close; listBox1.get_Items.Clear; addListItem(&quot;File written to C:\\KBTest.txt&quot;); }

// Get file properties. private void button3_Click (System.Object sender, System.EventArgs e)     { System.IO.FileInfo fileProps = new System.IO.FileInfo(winDir + &quot;\\notepad.exe&quot;); listBox1.get_Items.Clear; addListItem (&quot;File Name = &quot; + fileProps.get_FullName); addListItem (&quot;Creation Time = &quot; + fileProps.get_CreationTime); addListItem (&quot;Last Access Time = &quot; + fileProps.get_LastAccessTime); addListItem (&quot;Last Write Time = &quot; + fileProps.get_LastWriteTime); addListItem (&quot;Size = &quot; + fileProps.get_Length); fileProps = null; }

// Get drives. private void button4_Click (System.Object sender, System.EventArgs e)     { int loop, size; System.String[] drive = System.IO.Directory.GetLogicalDrives; size = drive.length; listBox1.get_Items.Clear; for (loop = 0; loop < size; loop ++) addListItem(drive[loop].ToString); }

// Get a list of folders. private void button5_Click (System.Object sender, System.EventArgs e)     { int loop, size; System.String[] dir = System.IO.Directory.GetDirectories(winDir); size = dir.length; listBox1.get_Items.Clear; for (loop = 0; loop < size; loop ++) addListItem(dir[loop].ToString ); }

// Get files. private void button6_Click (System.Object sender, System.EventArgs e)     { int loop, size; listBox1.get_Items.Clear; System.String[] file = System.IO.Directory.GetFiles(winDir); size = file.length; for (loop = 0; loop < size; loop ++) addListItem(file[loop].ToString); }

}                   </li> Press the F5 key to build and run the application. Click the buttons to observe the different actions. When you view the sample code, you may want to &quot;collapse&quot; the region titled &quot;Windows Form Designer Generated Code&quot; to hide this code.</li></ol>

back to the top

Keywords: kbhowtomaster kbinfo kbio kbfaq kbfileio KB323168

-

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

© Microsoft Corporation. All rights reserved.