Check out and contribute to CodePedia, the wiki for developers.

C# School

By Faraz Rasheed
Last Updated: Monday, November 03, 2008
Covers all you need to know to start programming in .NET and C#, from the basics to advanced topics.
starstarstarstarhalf star
                     Next Page



Working With The File System & Streams

If you are new to C# School
This is the final lesson of our C# School. The C# School is a kind of interactive learning platform where those who want to learn .NET with C# can find help and support. With one issue a week, describing some areas of the C# Programming Language with the Microsoft .Net Platform, this is not the same traditional passive tutorial where the author only writes and the reader only reads. There will be exercise problems at the end of each issue, which the reader is expected to solve after reading the issue. The solution to these problems will be provided in the next issue for testing purposes. There is also a dedicated message board attached with the school, where you can ask questions about the article, and the author will respond to your question within 2/3 days. You can send your suggestions, feedback or ideas on how these lessons can be improved to either the Author ( farazrasheed@acm.org)or the WEBMASTER ( info@programmersheaven.com).

For previous lessons: Lesson Plan
Today we will learn how we can manipulate the Windows file system and different types of streams using C# and .Net. We will start out by looking at how we can manipulate physical drives, folders and files, and perform different operations on them. In the second half of the lesson, we will explore the different types of streams used in .Net and see how we can read data from and write data to files. Finally we will learn about the concept of serialization of objects and how we can implement serialization in C#. The lesson also contains a supplementary topic on Asynchronous I/O.

Working with the File System
This section is further divided into three parts. In the first part, we will see how we can get the software system’s environment information, e.g. the path to the Windows System folder & the Program Files folder, current user name, operating system version, etc. In the second part, we will learn how to perform common file operations such as copying, moving, deleting, renaming and more. In the last part of this section, we will explore directory (or Folder) manipulation techniques.

Obtaining the Application’s Environment Information – The System.Environment class
The System.Environment class is the base class used to obtain information about the environment of our application. The description of some of its properties and methods is presented in the following table:

MemberDescription
CurrentDirectoryGets or sets the directory name from which the process was started
MachineNameGets the name of computer on which the process is currently executing
OSVersionReturns the version of current Operating System
UserNameReturns the user name of the user executing this process
VersionReturns a System.Version object representing the complete version information of the common language runtime (CLR)
Exit()Terminates the current process, returning the exit code to the Operating System
GetFolderPath()Returns the complete path of various standard folders of the windows operating system like Program files, My documents, Start Menu and etc.
GetLogicalDrives()Returns an array of type string containing the list of all drives present in the current system.


Demonstration Application – Environment Information
Let’s make a demonstration application that uses the above mentioned properties and methods to display environment information. It is a windows application project that contains a list box named ‘lbx’ which is used to display the information, a button named ‘btnGo’ which will be used to start fetching the information and a button named ‘btnExit’ which terminates the application. The main logic is present inside the Go button's event handler:

private void btnGo_Click(object sender, System.EventArgs e)
{
    OperatingSystem os = Environment.OSVersion;
    PlatformID OSid = os.Platform;
    string[] drives = Environment.GetLogicalDrives();
    string drivesString = "";
    foreach(string drive in drives)
    {
           drivesString += drive + ", ";
    }
    drivesString = drivesString.TrimEnd(' ', ',');
    lbx.Items.Add("Machine Name:       \t" + Environment.MachineName);
    lbx.Items.Add("Operating System:   \t" + Environment.OSVersion);
    lbx.Items.Add("Operating System ID:\t" + OSid);
    lbx.Items.Add("Current Folder:     \t" + Environment.CurrentDirectory);
    lbx.Items.Add("CLR Version:        \t" + Environment.Version);
    lbx.Items.Add("Present Drives:     \t" + drivesString);
}


Here we have simply retrieved the environment information from public properties and methods and added them to the list box. A few important things to note here are:
  • Environment.GetLogicalDrives() returns an array of strings, with each string representing the drive name.
  • Environment.Version returns an object of type System.Version which contains the detailed information about the current version of the common language runtime (CLR).
The event handler for exit button simply calls the Exit() method of the Environment class to terminate the current process.

private void btnExit_Click(object sender, System.EventArgs e)
{
  Environment.Exit(0);
}


Here we have passed zero to the Exit() method. This value will be returned to the Operating System and can be used to check whether the program terminates successfully or not.

When I executed this program to my system, I got the following result:

http://www.programmersheaven.com/articles/faraz/lesson15_img1.gif



                     Next Page




Bookmark: Submit To Digg Submit To reddit Submit To del.icio.us Bookmark With StumbleUpon Bookmark With FaceBook Bookmark With Google Bookmarks
Comments 55 Comments (view all) Post Comment Post a Comment
Joules Castillon says: Student
Edge Posted on Friday, June 13, 2003Edgestarstarstarstarstar
Great master piece... I have never imagined of such programming like Turbo C#... I am expecting that it would be Turbo D... It's an excellent advancement in Computer Science
mkn says: Good Work
Edge Posted on Friday, June 13, 2003Edgestarstarstar
Great stuff for biginners and had a good look of language key elements. Hopefully, the next aritcle will be more interesting.
Asim Ali says: Keep writing !
Edge Posted on Friday, June 13, 2003Edgestarstarstarstarstar
It was really nice to know about the article and it was more nice to read .
says: 5 STAR
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
Good effort. This will help us to improve our knowledge in the IT field thank u
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
This text summarizes the .NET architecture, its features like CLR, CLS, CTR. It contains a good comparison between C++, C# and Java. Better than what many books have tried to do.
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
No doubt the author, Faraz Rasheed , is a master mind. He is one of the best programmers in the university. The way he looks at Object Oriented techniques is really great, out of this world. I was surprised (and was proud too) when I saw him favoring C# in a discussion forum (Vs Java & C++) , which he won too :p Well Best of luck in future Faraz. We all are praying for you.
says: Good work
Edge Posted on Sunday, June 15, 2003Edgestarstarstarstarstar
This course is one of its type and has no parallel. Go ahead , Good Work!!!!!!!! Must continue to work on it with the same zeal:)
Sanjeev Ranjan says: A simple and nice code
Edge Posted on Tuesday, June 17, 2003Edgestarstarstarstarstar
Its a very simple and very easy written code. If any one is new then its good for them also. His explznztion is like a teaching lession in the class. I never seen better then this type of explanations.
Muhammad Adeel says: Great Work
Edge Posted on Tuesday, June 17, 2003Edgestarstarstarstarstar
Its a nice way and very helpful to those who really want to learn.
Syed Tahir Rasul says: wonderfully Awesome
Edge Posted on Wednesday, June 18, 2003Edgestarstarstarstarstar
Well, this is a great article to read at ProgrammersHeavan, one of the great assets on this site. Thank you Fraz
 
Popular resources and forums for programmers on Programmersheaven.com
Assembly, Basic, C, C#, C++, Delphi, Java, JavaScript, Pascal, Perl, PHP, Python, Ruby, Visual Basic
© Copyright 2009 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Publisher: Lars Hagelin. Read the latest words from the publisher here.
Be the first to sign up for Lars Hagelin’s In-depth Outsourcing Newsletter here.
bootstrapLabs Logo A bootstrapLabs project.