Monday, November 26, 2007

Creation of Directories in .NET

Creating a Directory
The Directory, DirectoryInfo, File and FileInfo classes in the .NET Base Class Library provide a simplified and powerful access to the files and directories in your System.
System.IO provides all the necessary classes, methods, and properties for manipulating Directory and files. In order to utilize the various methods within System.IO, users attempting to perform these operations must also have the required permissions to accomplish these types of actions; if they do not, a SecurityException will be thrown. Below you will find the main classes under this namespace.
Class Purpose/Use
1. BinaryReader and BinaryWriter - Read and write binary data.
2. Directory, File, DirectoryInfo, and FileInfo - Create, delete, and move files or directories. You can retrieve specific information about the files or folder by using of the properties defined in these classes.
3. FileStream - Access the files in a random order.
4. MemoryStream - Access data stored in memory.
5. StreamWriter and StreamReader - Read and write textual information.
6. StringReader and StringWriter - Read and write textual Information from a string buffer.
If you have ever run across a requirement to create a directory on the Server running your application, the System.IO namespace provides everything you need to accomplish such a task. Here I will show you two way to create a directory named MyDirectory on the C: Drive.
using System;
using System.IO;
namespace SystemIO
{
///

///

public class Yahiya
{
static void Main(string[] args)
{
CreateDirectory1();
}
public static void CreateDirectory1()
{
System.IO.Directory.CreateDirectory(@"C:\MyDirectory");
}
public static void CreateDirectory2()
{
string directoryPath = @"c:\MyDirectory";
System.IO.DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
}
}
The first method, CreateDirectory1, simply utilizes the CreateDirectory method that takes a string parameter. In my case I passed in @"C:\MyDirectory".
The second method, CreateDirectory2, performs exactly the same action as CreateDirectory1 with the only differences being I assigned @"C:\MyDirectory" to a string variable named directoryPath and then passed this variable into the CreateDirectory method.
Now that you are armed with the basics of creating a directory, we will now move into how to check if the directory in fact exist before we attempt to create it.

1 comment:

Anonymous said...

It is really good thanx dude