How to execute basic file I/O in Visual C #

Source: Internet
Author: User
Demonstrate file I/O operations


The example in this article describes basic file I/O operations. The step-by-step example section describes how to create an example program that demonstrates the following six file I/O operations:

Read text files
Write a text file
View File Information
List disk drives
List folders
List objects

Note:: If you want to use the following sample code directly, note the following:

Must includeSystem. IoThe namespace is as follows:

using System.IO;

Declare as followsWindirVariable:

string    winDir=System.Environment.GetEnvironmentVariable("windir");

Declare as followsAddlistitemFunction:

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

Note:: You can directly use the following statements without declaring and using them.AddlistitemFunction:

this.listbox1.Items.Add(value);"

Read text files


Use the following sample codeStreamreaderClass to read the system. ini file. The content of this file is added toListBoxControl. TheTry... catchBlocks are used to send alerts to programs when files are empty. There are multiple ways to determine whether the end of the file is reached; this example usesPeekMethod: Check the row before reading the row.

    StreamReader reader=new  StreamReader(winDir + "//system.ini");        try           {                do            {                addListItem(reader.ReadLine());            }               while(reader.Peek() != -1);        }                       catch         {             addListItem("File is empty");}        finally        {            reader.Close();        }

Write a text file


This sample code usesStreamwriterClass to create a file and write information. If an existing file already exists, 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");

View File Information


This sample code usesFileinfoObject. Notepad.exe is used in this example. Attribute inListBoxControl.

    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.LastWriteTime);    addListItem("Size = " + FileProps.Length);    FileProps = null;

List disk drives


Use this sample codeDirectoryAndDriveClass to list the logical drives on the system. The results in this example are displayed inListBoxControl.

    string[] drives = Directory.GetLogicalDrives();    foreach(string drive in drives)    {        addListItem(drive);    }

List subfolders


Use this sample codeDirectoryClassGetdirectoriesMethod to obtain the folder list.

    string[] dirs = Directory.GetDirectories(winDir);    foreach(string dir in dirs)        {            addListItem(dir);        }

List objects


This example usesDirectoryClassGetfilesMethod to obtain the folder list.

    string[] files= Directory.GetFiles(winDir);    foreach (string i in files)    {        addListItem(i);    }

Multiple errors may occur when users access files. The file may not exist or may be in use, or the user has no permission to access the files in the folder to be accessed. It is important to consider these possibilities when writing code and handling possible exceptions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.