HOW TO: Perform basic file IO (from MSDN) in Visual C # .NET

xiaoxiao2021-03-06  58

The release number of this article has been CHS304430

For Microsoft Visual Basic .NET versions of this article, see

CHS304427.

This task content

summary

Requires discussion of file I / O operations

Read text file Write text file View File Information List Disk Drive List Subfolders List File Separation Example

Summary The step-by-step process in this article demonstrates how to perform six basic file input / output (I / O) operations in Visual C # .NET. If you are in contact .NET, you will find that the file operation object model in .NET is familiar with many Visual Studio 6.0 developers.

FileSystemObject (fso) is very similar. In order for you to transition easier, this article demonstrates the following Microsoft Knowledge Base Article:

186118 HOWTO: USE FileSystemObject with Visual Basic (using filesystemObject in Visual Basic) can still be used in .NET.

FileSystemObject. because

FileSystemObject is a Component Object Model (COM) component, so .NET requires access to this object to pass through the Interope layer. If you choose to use this component, .NET will generate a package for it. However, if the FSO will not have the .NET framework without passing the interoP layer.

File,

FileInfo,

Directory and

DirectoryInfo class and other related classes.

Back to top

Requirements The recommended hardware, software, network structure, and service pack 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) Quick Start

Back to top

Discussion Demoned Document I / O Operation This example is introduced to basic file I / O operations. "Separation Example" section tells how to create a sample application that demonstrates the following six file I / O operations:

Read text file Write text file View File Information List Disk Drive List Folder List File

Note: If you want to use the following code examples directly, pay attention to the following:

The system.io namespace must be included, as shown below: Using system.io; WINDIR variable should be declared as follows: String WINDIR = System.Environment.GetenvironmentvironmentVariable ("windir"); addListItem function should be declared as follows: Private Void AddListItem String Value

{

THISTBOX1.Items.Add (value);

} Note: You can use the following statements directly without claiming and using the AddListItem function: this.listbox1.items.add (value); "

Back to top

Read the code sample below the text file

The StreamReader class reads the System.ini file. The content of the file is added to

ListBox controls. one of them

The Try ... catch block issues an alert to the program when the file is empty. There are a variety of ways to determine if the file end is reached; this example is used

The PEEK method checks the line before reading the next line.

StreamReader Reader = New StreamReader (WINDIR "//system.ini"" ;TRY

{

DO

{

AddListItem (Reader.Readline ());

}

While (reader.peek ()! = -1);

}

Catch

{

AddListItem ("File Is Empty");

Finally

{

Reader.Close ();

}

Back to top

Writing text file This code example is used

StreamWriter class creates and writes files. If there is an existing file, you can open it in the same way.

StreamWriter Writer = New StreamWriter ("c: //kbtest.txt");

Writer.writeline ("File Created Using Streamwriter Class.");

Writer.close ();

This.listbox1.items.clear ();

AddListItem ("File Written to C: //kbtest.txt");

Back to top

View file information This code example is used

FileInfo object Access the properties of the file. This example is used in NOTEPAD.EXE. Attribute

Displayed in the ListBox control.

Fileinfo fileprops = new fileinfo (windir "//notepad.exe");

AddListItem ("File Name =" FileProps.FullName);

AddListItem ("CREATION TIME =" FileProps.creationTime);

AddListItem ("Last Access Time =" FileProps.lastaccesstime);

AddListItem ("Last Write Time =" FileProps.lastwrittime);

AddListItem ("SIZE =" FileProps.Length);

FileProps = NULL;

Back to top

List the disk drive this code example

Directory and

The DRIVE class lists the logical drives on the system. The results in this example are

Displayed in the ListBox control.

String [] drivers = Directory.getLogicalDrives ();

Foreach (String Drive In Drives)

{

AddListItem (DRIVE);

}

Back to top

List subfolders This code example is used

Directory class

GetDirectories method Gets a folder list.

String [] DIRS = Directory.getdirectories (WINDIR);

FOREACH (String Dir in DIRS)

{

AddListItem (DIR);

}

Back to top

List the file this code example

Directory class

GetFiles method Gets a list of files.

String [] Files = Directory.getFiles (WINDIR);

FOREACH (String i in files)

{

AddListItem (i);

} There may be multiple errors when users access the file. For example, the file may not exist, may be in use, or no access to files in the folder attempt to access. These possibilities are important to consider these possibilities when writing codes and abnormalities that may be generated.

Back to top

Step-by-step examples In Visual C # .NET, start a new Windows application. Create Form1 by default. Open the FORM1 code window. Delete all the code in the Code Hide Editor. Paste the following code into the Code Hide Editor window. Using system;

Using system.drawing;

Using system.collections;

Using system.componentmodel;

Using system.windows.forms;

Using system.data;

Using system.io;

Namespace FSO_CS

{

///

/// summary description for Form1.

///

Public Class Form1: 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 button;

String WINDIR = System.Environment.GetenvironmentVironmentVariable ("WINDIR");

Private system.windows.forms.listbox listbox1;

///

/// Required Designer Variable.

///

Private system.componentmodel.Container Components = NULL;

Public Form1 ()

{

//

// Required for Windows Form Designer Support.

//

InitializationComponent ();

//

// to do: Add Any Construction Code After InitializationComponent Call.

//

}

///

/// Clean Up Any Resources Being Used.

///

Protected Override Void Dispose (Bool Disposing)

{

IF (Disposing)

{

IF (Components! = NULL)

{

Components.dispose ();

}

}

Base.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 vidinitiRizeComponent ()

{

This.button1 = new system.windows.Forms.Button ();

This.button2 = new system.windows.Forms.Button (); this.button3 = new system.windows.Forms.Button ();

This.listbox1 = new system.windows.forms.listbox ();

This.button4 = new system.windows.Forms.Button ();

This.button5 = new system.windows.Forms.Button ();

This.button6 = new system.windows.forms.button ();

THIS.SUSPENDLAYOUT ();

//

// Button1

//

This.button1.location = new system.drawing.point (216, 32);

This.button1.name = "button1";

This.button1.size = new system.drawing.size (112, 23);

This.button1.tabindex = 1;

This.Button1.Text = "Button1";

This.Button1.click = new system.eventhandler (this.button1_click);

//

// Button2

//

This.button2.location = new system.drawing.point (216, 64);

This.Button2.name = "button2";

This.button2.size = new system.drawing.size (112, 23);

This.button2.tabindex = 2;

This.button2.text = "button2";

This.button2.click = new system.eventhandler (this.button2_click);

//

// Button3

//

This.Button3.Location = new system.drawing.point (216, 96);

This.button3.name = "button3";

This.button3.size = new system.drawing.size (112, 23);

this.button3.tabindex = 3;

This.Button3.Text = "Button3";

This.Button3.click = new system.eventhandler (this.button3_click);

//

// ListBox1

//

This.listbox1.location = new system.drawing.point (24, 24);

this.listbox1.name = "listbox1";

This.listbox1.size = new system.drawing.size (176, 199);

this.listbox1.tabindex = 0;

//

// Button4

//

This.button4.location = new system.drawing.point (216, 128);

This.button4.name = "button4";

This.Button4.size = new system.drawing.size (112, 23); this.button4.tabindex = 4;

This.button4.text = "button4";

This.button4.click = new system.eventhandler (this.button4_click);

//

// Button5

//

This.button5.location = new system.drawing.point (216, 160);

This.button5.name = "button5";

This.Button5.size = new system.drawing.size (112, 23);

This.button5.tabindex = 5;

This.button5.text = "button5";

This.button5.click = new system.eventhandler (this.button5_click);

//

// Button6

//

This.button6.location = new system.drawing.point (216, 192);

This.button6.name = "button6";

This.button6.size = new system.drawing.size (112, 23);

This.button6.tabindex = 6;

This.button6.text = "button6";

This.button6.click = new system.eventhandler (this.button6_click);

//

// Form1

//

THIS.AUTOSCALEBASESIZE = New System.drawing.size (5, 13);

This.ClientSize = new system.drawing.size (360, 273);

this.controls.addrange (new system.windows.forms.control] {

this.button6,

this.button5,

this.button4,

this.button3,

this.button2,

this.button1,

This.listbox1});

THIS.NAME = "Form1";

THIS.TEXT = "Form1";

This.Load = New System.EventHandler (this.form1_load);

This.ResumeLayout (false);

}

#ndregion

///

/// The main entry point for the application.

///

[Stathread]

Static void main ()

{

Application.run (New Form1 ());

}

Private void button6_click (Object Sender, System.Eventargs E)

{

// How to Obtain List of Files (Example Uses Windows Folder).

This.listbox1.items.clear ();

String [] Files = Directory.getFiles (WINDIR);

FOREACH (STRING IIN Files) {

AddListItem (i);

}

}

Private void Button1_Click (Object Sender, System.Eventargs E)

{

//How to read a text file.

//Try...catch is to deal with a 0 byte file.

This.listbox1.items.clear ();

StreamReader Reader = New StreamReader (Windir "//system.ini");

Try

{

DO

{

AddListItem (Reader.Readline ());

}

While (reader.peek ()! = -1);

}

Catch

{

AddListItem ("File Is Empty");

Finally

{

Reader.close ();

}

Private Void Form1_Load (Object Sender, System.EventArgs E)

{

This.button1.text = "read text file";

This.Button2.text = "Write text file";

This.Button3.Text = "View file information";

THIS.BUTTON4.TEXT = "List drives";

This.Button5.Text = "List subfolders";

This.Button6.Text = "List files";

}

Private void button5_click (Object Sender, System.Eventargs E)

{

// How to get 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 button4_click (Object Sender, System.Eventargs E)

{

// Demonstrates How To Obtain A List of Disk Drives.

This.listbox1.items.clear ();

String [] drivers = Directory.getLogicalDrives ();

Foreach (String Drive In Drives)

{

AddListItem (DRIVE);

}

}

Private void button3_click (Object Sender, System.Eventargs E)

{

//How to Retrieve File Properties (Example Usess Notepad.exe).

This.listbox1.items.clear ();

Fileinfo fileprops = new fileinfo (windir "//notepad.exe");

AddListItem ("File Name =" FileProps.FullName);

AddListItem ("CREATION TIME =" FileProps.CreationTime); AddListItem ("Last Access Time =" FileProps.lastaccesstime);

AddListItem ("Last Write Time =" FileProps.lastwrittime);

AddListItem ("SIZE =" FileProps.Length);

FileProps = NULL;

}

Private Void AddListItem (String Value)

{

THISTBOX1.Items.Add (value);

}

Private void button2_click (Object Sender, System.Eventargs E)

{

// Demonstrates how to create and write to a text file.

StreamWriter Writer = New StreamWriter ("c: //kbtest.txt");

Writer.writeline ("File Created Using Streamwriter Class.");

Writer.close ();

This.listbox1.items.clear ();

AddListItem ("File Written to C: //kbtest.txt");

}

}

}

Press F5 to generate and run this application. Click the button to observe different operations. When viewing a code example, you may want to "fold" the area labeled "Windows Form Designer Generated Code" to hide this code.

Back to top

The information in this article applies to:

Microsoft Visual C # .NET (2002)

Recent Updated: 2002-2-15 (1.0) Keyword Kbhowto KbhowTomaster KB304430

转载请注明原文地址:https://www.9cbs.com/read-109109.html

New Post(0)