Manipulating Directories with the Directory Object


Manipulating directories (folders) is similar to manipulating files. However, instead of using System.IO.File, you use System.IO.Directory. If any of these method calls confuse you, refer to the previous section on System.IO.File for more detailed information. The following are the method calls:

  • To create a directory, call the CreateDirectory() method of System.IO.Directory and pass the name of the new folder, like this:

    System.IO.Directory.CreateDirectory(@"c:\my new directory");

  • To determine whether a directory exists, call the Exists() method of System.IO.Directory and pass it the directory name in question, like this:

    MessageBox.Show(Convert.ToString(System.IO.Directory.Exists(@"c:\temp";)));

  • To move a directory, call the Move() method of System.IO.Directory. The Move() method takes two arguments. The first is the current name of the directory, and the second is the new name and path of the directory. When you move a directory, the contents of it are moved as well. Note that the current directory and new directory must have identical rootsthat is they must be on the same drive. The following illustrates a call to Move():

    System.IO.Directory.Move(@"c:\current directory name",       @"d:\new directory name");

  • Deleting directories is even more perilous than deleting files because when you delete a directory, you also delete all files and subdirectories within the directory. To delete a directory, call the Delete() method of System.IO.Directory and pass it the directory to delete as well as TRue for the second parameter, which indicates a recursive delete. I can't overstate that you have to be careful when calling this method; it can you get you in a lot of trouble. The following statement illustrates deleting a directory:

    System.IO.Directory.Delete(@"c:\temp", true);




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

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