12.12 Creating a Directory

 <  Day Day Up  >  

You want to create a new directory on the file system.


Technique

To create a new directory, call the static method CreateDirectory defined in the Directory class. This method uses a single string denoting the full path of the directory to create. The path itself must be absolute, which means you cannot specify a new directory relative to the currently selected directory. To simulate a relative path , concatenate the results of calling Directory.GetCurrentDirectory with the relative path of the new directory to create. Additionally, the path itself can contain several subdirectories, which you specify by using the forward slash character ( \ ) to separate the values, as shown in the following code:

 
 private string CreateTempDirectory( string logFile ) {     DirectoryInfo di = Directory.CreateDirectory(         Directory.GetCurrentDirectory() + @"\temp\log" );     Directory.SetCurrentDirectory( di.FullName );     return Directory.GetCurrentDirectory(); } 

One thing you'll notice is that the CreateDirectory method returns a DirectoryInfo object. This object is explained in greater detail in Recipe 12.13, "Retrieving Directory Information." The DirectoryInfo class contains a method named CreateSubdirectory , allowing you to specify a relative path to create additional subdirectories.

Comments

A hard-coded path is a string within code that refers to a directory on your own system. Usually, this directory isn't on anyone else's machine because computers support multiple users and keep user directories to enforce data separation. The Directory class makes working with directories virtually trivial.

Even though directories are easy to work with, they can spell disaster at the touch of a button. When you are performing file operations, you should always be wary of the current directory, making sure that you add necessary error handling in case something were to go wrong. We could tell the anecdote of a colleague who wrote a recursive file-deletion algorithm and accidentally wiped out a couple of team member's hard drives , but we've already said enough. In short, don't take directories for granted, and always ensure that your code is accessing the proper locations at all times.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net