HOME  |    TRAINING  |   FREE TUTORIALS   |   JOBS
Find out more about our new RSS feed.
FREE Tutorial
C# PROGRAMMING: NAMESPACES AND THE BASE CLASSES PART 4 - FILE AND FOLDER OPERATIONS

CATEGORY
SEARCH OUR OTHER TUTORIALS

DESCRIPTION

One of the most common things you'll need to do is access the file system, to read and write to files, to move or copy files around, or to explore folders to check what files are there.
Click here to be kept informed of our new Tutorials.


This free tutorial is a sample from the book C# Programming with the Public Beta.


The .NET base classes include a number of classes that provide a rich set of functionality to do these tasks. These classes are contained in the System.IO namespace. Since the AppWizard doesn't add code to refer to this namespace by default, we add the line using System.IO near the top of the Form1.cs source file for all the samples in this section:

namespace Wrox.SampleCode.CSharpPreview.ChBaseClasses
{
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.WinForms;
using System.Data;
using System.IO;

Note that (as you can find out from the WinCV tool) these classes are still defined in mscorlib.dll, so we don't need to add any files to the project references.

Finding Out Information About a File

Our first file operations sample, which we'll call FileInfo will demonstrate how to get information about a file, such as its last write time, and its size. To do this we use a class, System.IO.File. The code to obtain the information is as follows:

File fl = new File("C:\\dotNET Book\\Ch8_ADO.doc");
AddItem("Connected to file : " + fl.Name);
AddItem("In Folder: " + fl.Directory);
AddItem("Full path: " + fl.FullName);
AddItem("Is Directory: " + fl.IsDirectory.ToString());
AddItem("Is File: " + fl.IsFile);
AddItem("Last write time: " + fl.LastWriteTime.ToString());
AddItem("Size in bytes: " + fl.Length);

This code should be fairly self-explanatory. We construct a File instance by supplying the full path name of the location of the file in the file system, and the File instance then refers to that file, and we can simply read off a number of properties of it. In this case I'm binding to the file for one of the other chapters of this book, the ADO+ chapter. Note that \ by itself is interpreted as the start of an escape sequence in strings in C#, so we need to use \\ to represent a single backslash in the pathname. You can also use an alternative syntax, in which the @ character precedes the string, which indicates that characters should not be escaped. Hence you would write:

File fl = new File(@"C:\dotNET Book\Ch8_ADO.doc");

This code gives us this output.

In general you can use a File object to connect to either a file or a folder, although if you connect to a folder then attempting to access those properties that don't make sense for a folder (such as Length or LastWriteTime) will raise an exception.

Listing Files in a Folder

To explore the contents of a folder, we need another base class - in this case the class Directory also in the System.IO namespace. Note that the .NET base classes generally refer to folders as directories in class and method names. This corresponds to normal terminology on web sites and on Unix and Linux machines, as well as on Windows 3.1 when it was around, but can be confusing if you're used to Windows terminology, in which a folder is an item in the file system that contains files, and a directory is a more sophisticated complete information store (such as Active Directory). I'll continue to use the term folder in this chapter, in accordance with normal usage for the Windows file system.

The following code sample connects to the folder C:\dotNET Book and separately lists the files and folders in it.

Directory fl = new Directory("C:\\dotNET Book");
AddItem("Connected to folder: " + fl.Name);
AddItem("Full path: " + fl.FullName);
AddItem("Is Directory: " + fl.IsDirectory.ToString());
AddItem("Is File: " + fl.IsFile);

AddItem("");
AddItem("Files contained in this folder:");
File [] childfiles = fl.GetFiles();
foreach (File childfile in childfiles)
{
 AddItem(" " + childfile.Name);
}

AddItem("");
AddItem("Subfolders contained in this folder:");
Directory [] childfolders = fl.GetDirectories();
foreach (Directory childfolder in childfolders)
{
 AddItem(" " + childfolder.Name);
} 

This code starts off by showing that the way of connecting to a folder is the same as for a file, and that the Directory and File classes both share the Boolean IsDirectory and IsFile properties, which can be used to distinguish what the object is if you are unsure. This means that you do not know what an object is, you can for example bind to it as a file, then use the IsDirectory property to check if it is actually a folder - and re-bind to it as a Directory if IsDirectory returns true. The resulting code would look something like this:

File fl = new File("C:\\DotNET Book");
if (fl.IsDirectory == true)
{
 fl = null;
 Directory dr = new Directory("C:\\DotNET Book");
 // process as directory
}
else
{
 // process as file
}

In the above code we next use a method, GetFiles() to retrieve a list of the files in the directory. This method returns an array of File instances, each one already bound to a file - so we can use a foreach loop to iterate through the array and carry out whatever processing we need to do on each file. The Directory class has another method, GetDirectories(), which works in exactly the same way as GetFiles(), but returns an array of Directory instances that refer to each subfolder. In both cases in the sample we use these methods to simply display the names of the files and folders.

This code produces this output on my computer:

Copying and Deleting files

The next sample is the one in which we really get to have a bit of fun mucking about with the directory system. As usual, it's a Windows project in which we add the code to the form's constructor, though in this case there's no real output to display.

We start off by binding to the dotNET Book folder, and we create both a new empty file and a new empty subfolder there. Directory fl = new Directory("C:\\dotNET Book"); fl.CreateSubdirectory("SampleBackups"); fl.CreateFile("MyNewFile.txt"); We're not going to write anything to the file yet - we'll do that soon.

Next we bind to one of the files in the C:\dotNET Book folder, rename it and copy it:

File adofile = new File("C:\\dotNET Book\\Ch8_ADO.doc");
adofile.CopyTo("C:\\dotNET Book\\SampleBackups\\Ch8_Backup.doc");

Note that you should put the complete path in otherwise the file will be copied to the same directory as the executable.

Now we have a go at deleting things - first the file spec.doc, then the Samples folder.

File sparefile = new File("C:\\dotNET Book\\spec.doc");
sparefile.Delete();

Directory sparefolder = new Directory("C:\\dotNET Book\\Samples");
sparefolder.Delete(true);

The File.Delete() method doesn't take any parameters. The Directory.Delete() method has two overloads. One (which we haven't demonstrated here) takes no parameters and does a simple delete and the file or directory goes to the recycle bin. The other takes one parameter - a Boolean which indicates whether the delete operation is recursive, which in this case we've specified that it is. If we'd wanted the delete not to be recursive we'd have written:

sparefolder.Delete(false);

In that case if sparefolder contained subfolders an exception would be raised.

Continued...


NEXT PAGE



5 RELATED COURSES AVAILABLE
C# PROGRAMMING
At the end of this course, you will have learned the fundamental skills that are required to design and develop o....
C++ PROGRAMMING
Object oriented programming is fast becoming the leading software design methodology, with C++ becoming ever more....
C PROGRAMMING
This course is design to provide non-C programmers with the essential skills and knowledge necessary to allow the....
C PROGRAMMING IN THE UNIX ENVIRONMENT
This course will provide readers the knowledge to use many of the UNIX 'C' library facilities, interface with the....
MICROSOFT VISUAL C++ 5 AND THE MFC&T 32 BIT WINDOWS PROGRAMMING
A complete 32 bit programming course highlighting the main features regarding the Microsoft Visual C++ programmin....
 
0 RELATED JOBS AVAILABLE
CONTACT US
Thursday 4th December 2008  © COPYRIGHT 2008 - VISUALSOFT