Archive

Archive for January, 2009

Building a website the Big Brother way: Web Layout tutorial with Photoshop

January 6, 2009 scerrimark 2 comments

A couple of days ago I decided to put up a series of tutorials on a web site that I am building for my friend. I already created the logo and the colour palette (see here) now the next step is to create the web layout. So let’s not waste time and start straight away.

Like the logo tutorial I will start by showing the final result. This will help you understand things better. So here is the final result.

marfelweblayout

How do we achieve this? Open Photoshop and let’ start!! Create a new document with width of 768 pixels and height of 800 pixels and set the resolution to 300 pixels/inch (so that we can increase the image size without losing quality) as shown below.

newlayout

The next thing is to set the foreground color to the dark gray colour with hex code of 1E2528. Then press Alt+Backspace to fill the background with the colour. The next thing is to insert the logo that we created in the previous post. To do this we go to File -> Open and open the logo (the image not the PSD file). When the logo opens press Ctrl+A and then copy (press Ctrl+C). The go in the web layout file and press Ctrl+V. Now press V so that we move the logo in the left upper corner like this.

logolayout

The next step is to create the menu holder. This part is very important to the website because the user will navigate from this part. To create the menu holder we create a new layer and then choose the Rectangle Tool (press U). Name the new layer menuholder. Make sure that the colour is the dark gray as the background. Now draw a rectange under the logo that stretches from left to right of the page (keep some space from the edges) as shown below.

menuholder1

Of course like this nothing is showing because it is the same colour as the background. So we need to add some styling. To do this double click on the menuholder layer and a new window will pop up. Choose Gradient Overlay. In the Gradient Overlay options menu double click on the Gradient colour box which is this one:

gradientA new window pops up. Click on the two gradient colour boxes as shown in the image below and change the colours to 1E2528 and 5E6A6E respectively to produce the following gradient. Then press the reverse option to reverse the gradient.

gradient2

The result achieved should be similar to the following:

layout1

The next step is to actually create the menu. To do this we select the Horizontal Type Tool (or press T) then click anywhere and type in “Home”. The font colour that I used is white (FFFFFF), Arial, and size is 3.21pt. I repeat this process for the other menu items (“Shopping Cart”, “New Products”, and “Checkout”). Place the menu items under each other as shown here.

menuitems

The  next step is to create separators between the menu items. Create a new layer and name it menuseparators. Then press u and choose the Line Tool. Make sure that the colour is white (FFFFFF), and that the size is 1px. Draw a line between the first menu item and the second. Then double click on the layer and choose Outer Glow as a style. The last thing is to change the opacity (from the Layer’s menu with the layer chosen) of the layer to around 33%.  Now duplicate this layer (Layer -> Duplicate Layer) two times and for each copy move the separator between menu items to produce the following result.

menuitems2

To have better division in the layout we will add 2 other separators between the logo and the menu holder and vertically near the menu items. Let’s start with the first one. Create a new layer and name it logoseparator. Then draw a line between the logo and the menu holder. Finally double click on the layer and choose Outer Glow effect then change the opacity to 33%. Repeat this process but this time draw a vertical line between the logo and the end of the menu holder near the menu items. The result should be as shown below.

separators

For the next step we are going to need the following image.

watch

Now insert this image and place it near the menu like in the image below. To resize it press Ctrl+T and to move it to the desired position press V. While resizing it press the Shift key so that the dimensions remain proportionate.

watchlayout

Now we insert a small description near the watch by using the Horizontal Type Tool (T). I used Arial for the font and I mixed the gold and white colour for the text. With some experimenting I achieved the following result.

watchlayout2

The next step is to add a button so that users can see more details about this watch. To do this create a new layer and name it button. Then set the colour to 5A676C and draw a small rectangle under the price (press U for the rectangle tool). Then double click on the layer and choose Drop Shadow as an effect. Finally add “More Details” text on the button and you should have something like this. The font size is 3.4pt.

watchlayout3

The final touch for the menu holder will be to add two lines at the bottom of the menu holder to a new layer that we will name headerlines. To add lines press U and select the line tool. The first line should be 1px and the second 2px. The colours should be 6a7378 and cfb52b respectively. The lines are shown below.

lines

So the header is finished. No we need to focus on the main part of the website. To do this create a new layer and name it mainpart. Then draw a white rectangle in it and place it on the right hand side under the menu holder. Then create another layer and name it mainseparator. In it draw a vertical line with the 6a7378 colour. Repeat this last step 2 more times. Now we have three lines with which we are going to separate the main part in 3 parts to achieve this result.

mainpart

The next thing is to add some products to the website. For this you need the following 3 pictures.

watch1watch2watch3

We are then going to put these 3 images, one in each column. To resize the images press Ctrl+T. Press Shift while resizing so that you keep the dimensions in proportion. Then under each watch add some text for the name, description, and price of the watches as shown in the image below. I used Arial as the font. The name and price of each watch is written in gold (cfb52b) and the description in gray(6a7378).

The next step is to include two buttons: Add to Cart and Details button. To do this we create a new layer and name it addtocart. Then make sure that the colour is 6a7378 and with the rectangle tool (U) draw a button under the price. Then double click on the layer and choose the Drop Shadow effect. The next thing is to write Add to Cart in white (ffffff) on the button. Now merge the last two layers (addtocart and the Add to Cart text layer). This is done by choosing the topmost layer (Add to Cart) and then going on Layer -> Merge Down (or Ctrl+E as a shortcut). Now move the button to the desired position. The last step is to duplicate the layer (Layer ->Duplicate Layer) twice so that we have a button for each watch. Move the buttons one under each watch.

Next repeat the above processes for the Details button. The only difference is that I did the Details button in gold (cfb52b). Here is the result.layout2

Now we need to fill the left part under the menu. Here we are going to put a list of brands. So let’s start with the holder first. Create a new layer and name it brandholder. Set the colour to gray 6a7378 and with the Rectangle Tool (U) draw a rectangle as the holder. Then double click on the layer and click Gradient Overlay effect and apply the following options.

gradient3

Then write Browse By Brand as a title at the top (do it bold and then write a number of brands as a list underneath as shown below. All text is in white (ffffff). You can also add a separator under the Browse By Brand title. All you need to do is duplicate (Layer -> Duplicate Layer) a menu separator and move it under the Browse By Brand.

brand

The last thing is to create the footer. To do this create a new layer and name it footer. Set the colour to our gray 6a7378. Then draw a rectangle with the Rectangle Tool (U) underneath the main part to act as a footer. Now apply a Gradient Overlay effect by double clicking on the footer layer with the following options.

gradient4

Now insert some logos and text in the footer as shown below. You can insert whatever you want in the footer. Try to experiment and be original. I came up with the following final result.

marfelweblayout

Well that’s all for today. The next step? Well the next step is converting this image to HTML, CSS, and JavaScript. Stay tuned things look very interesting. Until then here are a couple of books that will surely interest you:

Enjoy!!

Categories: Photoshop

C# .NET Tutorial 6: Reading and Writing Files

January 5, 2009 scerrimark Leave a comment

In the last couple of week I have been writing a number of C# tutorials. This is number 6 and today we will discuss reading and writing of files, two very common tasks in development. For those who are new the previous 5 tutorials can be found here.

Streams

Streams are used to write and read both sequential and random access data. These are the common properties of the Stream class in .NET:

  • CanRead – determines whether stream supports reading.
  • CanSeek – determines whether stream supports seeking.
  • CanTimeout – determines whether stream supports time out.
  • CanWrite – determines whether stream supports writing.
  • Length – returns the length in bytes of the stream.
  • Position – gets or sets the cursor to determine where in the stream the current position is.
  • ReadTimeout – gets or sets the stream’s time out for read operations.
  • WriteTimeout – gets or sets the stream’s time out for write operations.

The following are the Stream common methods:

  • Close – closes the stream and releases any associated resources with it.
  • Flush – clears any buffers within the stream and forces any changes to the stream to be written to the underlying system or device represented by the stream.
  • Read – performs a sequential read from the current position of a number of bytes and updates the position to the end of the read bytes.
  • ReadByte – reads one byte and updates the position by one.
  • Seek – sets the position within the stream.
  • SetLength – specifies the length of the stream.
  • Write – writes information to the stream as number of bytes and updates the current position to reflect the new write position.
  • WriteByte – writes a single byte to the stream and updates the position by one.

All the stream classes in .NET derive from the Stream class. These include:

  • FileStream (System.IO)
  • MemoryStream (System.IO)
  • CryptoStream (System.Security)
  • NetworkStream (System.Net)
  • GZipStream (System.Compression)

The reason these streams have the same base class is that working with data as a flow is a common way in different scenarios. Let’s start looking at some examples how to work with a stream. Learning to work with a stream means that you can apply that knowledge to any type of stream. To dump the contents of a stream on screen you use the following code:

//make sure we read from the beginning
theStream.Position = 0;
//Go through the entire stream and read byte by byte
while (theStream.Position != theStream.Length)
{
    Console.WriteLine("{0:x2}", theStream.ReadByte());
}

This code is able to work on any kind of stream. The next example is to send information to a stream:

theStream.Position = theStream.Length; //puts cursor at the end
theStream.Write(data, 0 , data.Length);

Classes for Reading and Writing data

A number of classes take part in the process of reading and writing files. One of these is the File class. This classes exposes static methods used for opening and creating classes. The File class can perform:

  • Atomic operations to read and write to files.
  • Operations to open files for reading or writing.
  • Simple file operations (File.Exists, File.Delete, etc.).

The File class can return a number of types with the FileStream being the most rudimentary. The File Class also has methods that return objects of type StreamReader and StreamWriter.These classes wrap a FileStream to support sequential reading and writing to a stream.

The File operations supported by the File Class are the same as the FileInfo class.

The MemoryStream is a special stream for manipulating data in memory. This stream is used to create stream objects in memory for optimization.

File Class

The File class is used to handle file streams for reading and writing. These are the most important File static methods:

  • AppendAllText – appends a string to a file. If the file does not exist it creates it.
  • AppendText – Opens a file and returns a StreamWriter that is prepared to allow text to be added to the file.
  • Copy – copies a file to a new file. The new file must not exist for Copy to be successful.
  • Create – creates a new file and returns a FileStream.
  • CreateText – creates or opens a file and returns a StreamWriter ready to have text written to it.
  • Move – moves a file from one place to another.
  • Open – opens an existing file and returns  FileStream object.
  • OpenRead – opens an existing file and returns a read-only FileStream object.
  • OpenText – opens an existing file and returns a StreamReader object.
  • OpenWrite – opens an existing file for writing and returns a StreamWriter object.
  • ReadAllBytes – opens a file, reads the content to a byte array, and closes the file in one atomic operation.
  • ReadAllLines – opens a file, reads the content line by line into an array of strings and closes the file in one atomic operation.
  • ReadAllText – opens a file, reads the content into a string, and closes the file in one atomic operation.
  • WriteAllBytes – opens a file, writes the content of a byte array in it, and closes the file in one atomic operation.
  • WriteAllLines – opens a file, writes the content from an array of strings into the file, and closes the file in one atomic operation.
  • WriteAllText – opens a file, writes the content into a string, and closes the file in one atomic operation.

Directory Class

Like the File class, the Directory class has a number of static methods to manipulate and create directories. These are the most important methods:

  • CreateDirectory – creates all directories in a supplied path.
  • Delete – deletes a specified directory.
  • Exists – determines whether a directory exists or not.
  • GetCreationTime – returns the time and date of creation of a directory.
  • GetCurrentDirectory – returns a DirectoryInfo object for the current working directory of the application.
  • GetDirectories – gets a list of names for subdirectories of a directory specified.
  • GetDirectoryRoot – returns the volume or root information for a specified directory.
  • GetFiles – returns the names of files in a directory.
  • GetFileSystemEntries – returns a list of files and subdirectories for a specified directory.
  • GetLastAccessTime – returns the time that a directory was last accessed.
  • GetLastWriteTime – returns the time that a specified directory was last written to.
  • GetLogicalDrives – creates a list of drives as strings in the format “C:\”.
  • GetParent – gets the parent directory of the specified directory.
  • Move – moves a file or directory to a specified place.
  • SetCreationTime – sets the time a specified directory was created.
  • SetCurrentDirectory – sets a specified directory to be the current working directory for the application.
  • SetLastAccessTime – sets the last time a directory was accessed.
  • SetLastWriteTime – sets the last time a directory was written to.

FileAccess Enumeration

The FileAccess enumeration provides members that are used to determine the access rights required when opening a file. These are:

  • Read
  • Write
  • ReadWrite

FileMode Enumeration

The FileMode Enumeration specifies how a file should be opened or created. These are:

  • Append – opens a file and moves the pointer in the FileStream object at the end. Can only be used with FileAccess.Write.
  • Create – creates a new file. If it exists it is overwritten.
  • CreateNew – creates a new file. If the file exists then it throws an exception.
  • Open – open an existing file. If the file does not exist, an exception is thrown.
  • OpenOrCreate – opens an existing file. If the file does not exist, it creates a new file.
  • Truncate – opens an existing file but empties the file so that it is zero bytes long.

FileStream Class

The FileStream class provides the functionality to open file streams for reading and writing. These are the most important methods:

  • CanRead – determines whether stream supports reading.
  • CanSeek – determines whether the stream supports seeking.
  • CanTimeout – determines whether the stream can time out.
  • CanWrite – determines whether the stream can write.
  • Handle – gets the stream’s underlying file handle.
  • Length – gets the length (bytes) of the stream.
  • Name – gets the name of the file.
  • Position – gets or sets the virtual cursor for determining where in the stream the current position is.
  • ReadTimeout – gets or sets the stream’s timeout for read operations.
  • WriteTimeout – gets or sets the stream’s timeout for write operations.
  • Close – closes the stream and releases any associated resources.
  • Flush – clears any buffers within the stream and forces any changes to be written to the underlying system or device.
  • Lock – prevents other processes from changing part of the file.
  • Read – performs a sequential read of a specified number of bytes and updates the position of the cursor accordingly.
  • ReadByte – performs a read of a single byte and updates the position of the cursor by one.
  • Seek – sets the position within the stream.
  • SetLength – specifies the length of the stream.
  • Unlock – lets other processes change the stream.
  • Write – writes sequentially a specified number of bytes and moves the cursor at the end.
  • WriteByte – writes one byte to the stream and moves the cursor one position.

StreamReader Class

The StreamReader class provides the functionality to read data from a Stream derived class. These are the important properties:

  • BaseStream – gets the underlying stream that the reader is reading.
  • CurrentEncoding – gets the current encoding used by the stream.
  • EndOfStream – determines whether the reader has encountered the end of the stream.

These are the most commonly used methods:

  • Close – closes the reader and the underlying stream.
  • Peek – returns the next character in the stream without moving the cursor.
  • Read – reads the next set of characters from the stream.
  • ReadBlock – reads the next block of characters from the stream.
  • ReadLine – reads the next line of characters in the stream.
  • ReadToEnd – reads all the characters through to the end of the stream.

How to Read a File in C#

Here is the code to open a file and read from it.

//first open the file
FileStream theFile = File.Open(@"C:\test.txt", FileMode.Open, FileAccess.Read);

//the File.Open returns a FileStream. We will create StreamReader that wraps the FileStream.
StreamReader reader = new StreamReader(theFile);

Console.WriteLine(reader.ReadToEnd());

//close reader and stream
reader.Close();
theFile.Close();

It is important to note that the StreamReader returns data as a string. The File class has additional methods that make it simpler to open a file for reading. The File class supports creating a StreamReader immediately without the need of wrapping a FileStream. This is done as follows.

StreamReader reader = File.Open(@"C:\test.txt");
Console.WriteLine(reader.ReadToEnd());
reader.Close();

If you want to read the whole file at one go then it can become even simpler as follows.

Console.WriteLine(File.ReadAllText(@"C:\test.txt"));

The last example shows code that is looking inside a file and finding a particular word (“test”).

StreamReader reader = File.Open(@"C:\test.txt");

while (!reader.EndOfStream)
{
    string line = reader.ReadLine();
    if (line.Contains("test"))
    {
        Console.WriteLine("Found test");
        break;
    }
}

StreamWriter Class

The StreamWriter class provides the functionality to write data to streams. The following are its important properties:

  • AutoFlush – gets or sets an indicator that shows whether every call to the Write method should flush changes to the underlying stream.
  • BaseStream – gets the underlying stream that the writer is writing.
  • Encoding – gets the encoding the underlying stream is using.
  • NewLine – gets or sets a string that contains the line terminator string. This is used only if you want to change the string that terminates every individual line.

The following are the most commonly used methods:

  • Close – closes the writer and the underlying stream.
  • Write – writes to the stream.
  • WriteLine – writes data to the stream followed by a string that terminates each individual line.

How to Write to a File in C#

The following is the code used to write to a file in C#.

StreamWriter writer = File.CreateText(@"C:\test.txt");
writer.WriteLine("Test");
writer.Close();

The StreamWriter can also write a chunk of text all at once.

File.WriteAllText(@"C:\test.txt", "Test1 Test2");

If you want to write to an existing file you use the follow code.

FileStream stream = File.OpenWrite(@"C:\test.txt");
StreamWriter writer = new StreamWriter(stream);
writer.Write("Hello World!");
writer.Close();
stream.Close();

Finally if you do not know whether a file exists or not but if it exists you want to append you use the following code.

FileStream stream = File.Open(@"C:\test.txt", FileMode.OpenCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);
writer.Write("Hello World!");
writer.Close();
stream.Close();

Understanding Readers and Writers

The StreamReader and StreamWriter classes inherit from the TextReader and TextWriter abstract classes respectively. There are other readers and writers. These are:

  • StringReader/StringWriter – read to and write from in-memory strings.
  • BinaryReader/BinaryWriter – used to handle getting binary data to and from streams.

MemoryStream Class

This class provides the functionality to create in-memory streams. The following are the most important properties:

  • CanRead – determines whether the stream supports reading.
  • CanWrite – determines whether the stream supports writing.
  • CanSeek – determines whether the stream supports seeking.
  • CanTimeout – determines whether the stream can time out.
  • Capacity – gets or sets the number of bytes allocated for the stream.
  • Length – gets the length (in bytes) of the stream.
  • Position – gets or sets the position of the cursor in the stream.
  • ReadTimeout – gets or sets the time out for the read operation of the stream.
  • WriteTimeout – gets or sets the time out for the write operation of the stream.

These are the main MemoryStream methods:

  • Close – closes the stream and releases any resources associated with it.
  • Flush – clears any buffers within the stream and forces changes to be written to the underlying system or device.
  • GetBuffer – retrieves the array of unsigned bytes that was used to create the stream.
  • Read – performs a sequential read of a specified number of bytes and updates the position of the cursor.
  • ReadByte – reads a byte and moves the cursor position by one.
  • Seek – sets the position within the stream.
  • SetLength – specifies the length of the stream.
  • ToArray – writes the entire stream to an array of bytes.
  • Write – writes a number of specified bytes to the stream and updates the cursor accordingly.
  • WriteByte – writes a byte of data into the stream and moves the cursor one position.
  • WriteTo – writes the MemoryStream to another stream.

How to Use the Memory Stream

Here is an example how to use the MemoryStream and then write it to a FileStream.

MemoryStream memStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memStream);
writer.WriteLine("Hello World");
//force the writer to push the data in the stream
writer.Flush();

FileStream theFile = File.Create(@"C:\test.txt");
memStream.WriteTo(theFile);
writer.Close();
theFile.Close();
memStream.Close();

The BufferedStream Class

The BufferedStream Class provides the basic functionality to wrap streams to improve performance by buffering reads and writes to the stream. Its most important properties and methods are the same as the MemoryStream.

How to use a BufferedStream

The BufferedStream should be used in situations when writing out data to a stream directly does not perform well. The following code demonstrates how to use a BufferedStream.

FileStream theFile = File.Create(@"C:\test.txt");
BufferedStream buffer = new BufferedStream(theFile);
StreamWriter writer = new StreamWriter(buffer);
writer.WriteLine("Hello");
writer.Close();

Well for today that is enough. In the next tutorial we will take a look at Compressed Streams. Until then bye bye!

Categories: C# .NET

C# .NET Tutorial 5: Navigating the File System

January 2, 2009 scerrimark 6 comments

Hello hope you are feeling fine and hope that you are looking forward for the new year. For those who are new this is number 5 of a series of C# tutorials. If you want to start from the beginning click on the C# category on the right and you will have all the tutorials in descending order. I recommend that you start from the first one and proceed from there. In the coming 4 tutorials ( 5 – 8 ) I will be talking about input and output in C# .NET. These include accessing files and folders on your system, reading and writing streams, compressing streams, and using isolated storage. In these four tutorials I am assuming that you can create a console application in Visual Studio (or Visual C# Express Edition), you can add references of class libraries to your project, and that you can create text files. So let’s start with the first tutorial.

The File System Classes

There are two sets of classes realted to the file system in the System.IO namespace. The first set is informational classes that all derive from the FileSystemInfo base class and are used to obtain information from the file system objects (files, directories, and drives). These classes are FileInfo, DirectoryInfo, and DriveInfo. The DriverInfo class does not inherit from the FileSystemInfo because it does not share the behaviour of files and directories. For example while you can delete files and folders, you cannot delete drives.

The utility classes, which include the File, Directory, and Path classes,  provide static methods to perform operations on files, directories, and file system paths.

FileSystemInfo Classes

The following are the properties of the FileSystemInfo class:

  • Attributes – gets or sets FileAttributes of the current file or directory.
  • CreationTime – gets or sets the time that the current file or directory was created.
  • Exists – checks whether a file or directory exist.
  • FullName – returns a full path for a file or directory.
  • LastAccessTime – gets or sets the time the file or directory was accessed.
  • LastWriteTime – gets or sets the time the file or directory was written to.
  • Name – returns the simple name.

The following are some of the commonly used methods in the FileSystemInfo class:

  • Delete – removes a file or directory from the system.
  • Refresh – updates the data in the class with the latest information from the file system.

FileInfo Class

This class provides the basic functionality to access and manipulate a single file in the system. The following are the most common properties:

  • Directory – returns the DirectoryInfo object that represents the directory in which this file is found.
  • DirectoryName – returns the name of the directory in which this file is found.
  • IsReadOnly – gets or sets the flag that determines whether a file can be modified or not.
  • Length – gets the length of the file.

The following are the important FileInfo methods:

  • AppendText – creates a new StreamWriter to append text to the file (will see in the next tutorial).
  • CopyTo – copies a file in a new location.
  • Create – creates a file.
  • CreateText – creates a new StreamWriter to create a text file.
  • Decrypt – decrypts a file that was encrypted by the current user.
  • Encrypt – encrypts a file so that only the current user can decrypt it.
  • MoveTo – moves a file to a new location.
  • Open – opens the file with specific privileges.
  • OpenRead – opens a file with read-only access.
  • OpenText – opens a file and returns a StreamReader to read from a text file.
  • OpenWrite – opens a file with write-only access.
  • Replace – replaces a file with the information in the current FileInfo object.

Get Information about a File

To get information about a file you need to:

  • Create a FileInfo object with the path of the file.
  • Accces the FileInfo object’s properties.

For example to check if a file exists you do the following:

FileInfo testFile = new FileInfo(@"c:test.dbf"); //the @ symbol is used so that the string is treated as is (raw).
if (testFile.Exists)
{
    Console.WriteLine("Filename: {0}", testFile.Name);
    Console.WriteLine("Path: {0}", testFile.FullName);
}

How to Copy a File

The FileInfo also let’s you do operations on the file. For example here we are making a copy of the file:

FileInfo testFile =  new FileInfo(@'c:test.dbf');
testFile.CopyTo(@"c:backuptest.dbf");

DirectoryInfo Class

This class provides the mechanism to access and manipulate a single directory on the file system. The following are the important properties of the DirectoryInfo class:

  • Parent – gets the DirectoryInfo for the parent directory of the current directory.
  • Root – gets the root part of the current directory as a string.

The following are the mostly used DirectoryInfo methods:

  • Create – creates a directory
  • CreateSubdirectory – creates a new directory as a child of the current directory
  • GetDirectories – returns an array of DirectoryInfo objects of the sub directories present in the current directory.
  • GetFiles – returns an array of FileInfo objects of all the files in the current directory.
  • GetFileSystemInfos – returns an array of FileSystemInfo objects that represents the files and directories in the current directory.
  • MoveTo – moves the current directory to a new location.

Enumerating Files in a Directory

To list the files in a directory you use the following code:

DirectoryInfo currentDir = new DirectoryInfo(@"C:backup");

foreach (FileInfo files in currentDir.GetFiles())
{
    Console.WriteLine("File: {0}", files.Name);
}

DriveInfo Class

To access and manipulate a single drive you use the DriveInfo class. Here are the commonly used properties:

  • AvailableFreeSpace – gets the amount of available space on the drive (can be different than TotalFreeSpace because of quotas).
  • DriveFormat – gets the format of the drive like NTFS, FAT32, etc.
  • DriveType – gets the type of drive in the form of DriveType enumeration.
  • IsReady – returns whether the drive can be accessed.
  • Name – returns the name of the drive.
  • RootDirectory – returns a DirectoryInfo object of the root directory of the drive.
  • TotalFreeSpace – gets the total amount of free space on the drive.
  • TotalSize – total size of the drive
  • VolumeLabel – gets or sets the label of the drive (set only if it is not readonly).

The most important method in the DriveInfo class is the GetDrives method which is a static method that returns all the drives on the system.

DriveType Enumeration

The DriveType enumeration provides the possible types of drives that can be stored in the DriverInfo class. These are:

  • CDRom – a cd or dvd drive.
  • Fixed – a fixed disk or hard drive disk.
  • Network – A network mapped drive.
  • NoRootDirectory – a drive without a root directory.
  • Ram – a RAM drive.
  • Removable – a drive that has removable media such as a USB drive.
  • Unknown

How To Enumerate Drives

To list all the drives you use the following code:

DriveInfo[] drives = DriveInfo.GetDrives();

foreach (DriveInfo drive in drives)
{
    Console.WriteLine("Drive: {0}", drive.Name);
    Console.WriteLine("Type: {0}", drive.DriveType);
}

Path Class

To manipulate a file system path you use the Path class. Here are some of its methods:

  • ChangeExtension – takes a path and returns a new path with the new extension (only the path string changes not the actual file extension).
  • Combine – combines two compatible path strings.
  • GetDirectoryName – returns the name of the directory in the specified path.
  • GetExtension – returns the name of the file extension in the specified path.
  • GetFileName – returns the name of the file in the specified path.
  • GetFileNameWithoutExtension – returns the name of the file without extension in the specified path.
  • GetFullPath – returns a full path of the specified path.
  • GetPathRoot – returns the root directory name in the specified path.
  • GetRandomFileName – generates a random file name.
  • GetTempFileName – generates a temporary file in the file system and returns it’s path.
  • GetTempPath – returns the path for the temporary file directory for the current user or system.
  • HasExtension – indicates whether a specified file path has an extension.
  • IsPathRooted – indicates whether a specified path includes a root directory.

How to Change a File Extension

Here is the code to change a file extension:

string path = @"C:test.dbf";

Console.WriteLine("Extension: {0}", Path.GetExtension(path));
Console.WriteLine("New Extension {0}", Path.ChangeExtension(path, "bak"));

FileSystemWatcher Class

The FileSystemWatcher class is used to monitor file system directories for changes. Here are some of it’s properties:

  • EnableRaisingEvents – gets or sets whether the watcher object should raise events. It is used to turn on or off the watching of a directory.
  • Filter – gets or sets the filter that determines which files to watch.
  • IncludeSubdirectories – gets or sets an indicator of whether the watching of a directory includes also the sub directory.
  • NotifyFilter – gets or sets the type of changes to watch for. By default all are watched for.
  • Path – gets or sets the path to the directory to monitor.

The most important method in the FileSystemWatcher class is the WaitForChanged method. This is a synchronous method for watching a directory for changes and for returning a structure that contains all the changes.

The following are the events related to the FileWatcherSystem class. The events are self-explanatory:

  • Changed
  • Created
  • Deleted
  • Renamed

How to Monitor Changes in a Directory

To monitor changes in a directory the following procedure needs to be used:

  • Create a new FileSystemWatcher object specifying the directory in the Path property.
  • Register for the events.
  • Turn on the events by setting EnableRaisingEvents to true.

The following code demonstrates this procedure:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:";

//Register for events
watcher.Created += new FileSystemEventHandler(watcherChanged);
watcher.Deleted += new FileSystemEventHandler(watcherChanged);

//turn on events
watcher.EnableRaisingEvents = true;

//Event handler
static void watcherChanged(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("Directory Changed");
}

When watching the file system you can get more changes than the FileSystemWatcher can handle. In such case the FileSystemWatcher will throw an Error event.

Well that’s the end for today’s tutorial. It was quite interesting right? Leave your comments and I will see you for the next tutorial on I/O – reading and writing files.

Categories: C# .NET Tags: