Microsoft KB Archive/323168

From BetaArchive Wiki

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

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 "Step-by-Step Example" 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("windir");
                        
  • 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 + "\\system.ini");
            
            // Clear box.
            listBox1.get_Items().Clear();

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

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

            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("c:\\KBTest.txt");

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

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 + "\\notepad.exe");
            listBox1.get_Items().Clear();
            addListItem ("File Name = " + fileProps.get_FullName());
            addListItem ("Creation Time = " + fileProps.get_CreationTime());
            addListItem ("Last Access Time = " +  fileProps.get_LastAccessTime());
            addListItem ("Last Write Time = " + fileProps.get_LastWriteTime());
            addListItem ("Size = " + 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

  1. In Visual J# .NET, start a new Windows application. By default, Form1 is created.
  2. Name the new Windows application TestIO.
  3. Right-click Form1, and then click View Code.
  4. Delete all of the code in the Code-Behind Editor.
  5. 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("windir");
    
          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("button1");
                this.button1.set_Size(new System.Drawing.Size(120, 56));
                this.button1.set_TabIndex(0);
                this.button1.set_Text("Read Text File");
                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("button2");
                this.button2.set_Size(new System.Drawing.Size(120, 56));
                this.button2.set_TabIndex(1);
                this.button2.set_Text("Write Text File");
                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("button3");
                this.button3.set_Size(new System.Drawing.Size(120, 56));
                this.button3.set_TabIndex(2);
                this.button3.set_Text("View File Information");
                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("button4");
                this.button4.set_Size(new System.Drawing.Size(120, 56));
                this.button4.set_TabIndex(3);
                this.button4.set_Text("List Drives");
                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("button5");
                this.button5.set_Size(new System.Drawing.Size(120, 56));
                this.button5.set_TabIndex(4);
                this.button5.set_Text("List Subfolders");
                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("button6");
                this.button6.set_Size(new System.Drawing.Size(120, 56));
                this.button6.set_TabIndex(5);
                this.button6.set_Text("List Files");
                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("listBox1");
                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("Form1");
                this.set_Text("Form1");
                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 + "\\system.ini");
                listBox1.get_Items().Clear();
                try 
                {
                     do
                     {
                          addListItem(reader.ReadLine());
                     }
                     while(reader.Peek () != -1);
                }
    
                catch (System.Exception error)
                {
                     addListItem ("File is empty");
                }
    
                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("c:\\KBTest.txt");
                writer.WriteLine("File created using the StreamWriter class");
                writer.Close();
                listBox1.get_Items().Clear();
                addListItem("File written to C:\\KBTest.txt");
          }
    
          // Get file properties.
          private void button3_Click (System.Object sender, System.EventArgs e)
          {
                System.IO.FileInfo fileProps = new System.IO.FileInfo(winDir + "\\notepad.exe");
                listBox1.get_Items().Clear();
                addListItem ("File Name = " + fileProps.get_FullName());
                addListItem ("Creation Time = " + fileProps.get_CreationTime());
                addListItem ("Last Access Time = " + fileProps.get_LastAccessTime());
                addListItem ("Last Write Time = " + fileProps.get_LastWriteTime());
                addListItem ("Size = " + 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());
          }
    
    }
                        
  6. 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 "collapse" the region titled "Windows Form Designer Generated Code" to hide this code.

back to the top

Keywords: kbhowtomaster kbinfo kbio kbfaq kbfileio KB323168