Support - Knowledge base

Giving you the answers you need

Why not try our knowledge base for instant help and advice to enhance your online experience with Register365? From within the knowledge base you can browse our frequently asked questions and find the right answers to help solve your queries.

Home  >  Scripting  >  ASP (Active Server Pages)  >  View Article

How to create a directory using ASP.NET code.

3*3*3*3*3*

Article

CreateDirectory() method of System.IO.Directory class has a security bug. If an account running the code has no read permissions on the root directory, the System.IO.Directory.CreateDirectory() method will fail. And you will get the following error:

Could not find a part of the path "<full directory path>"

The reason for this error is that System.IO.Directory.CreateDirectory() checks folder existence from root to the target folder. The code provided in this article performs the scan in the reverse way - from lowest to highest in the hierarchy. Therefore, it won't fail unless it finds a folder with no read permissions.

Using the code

To use the provided code, add Microsoft Scripting Runtime COM object to your project references.

public static void CreateDirectory(string DirectoryPath)
  {
      // trim leading \ character
      DirectoryPath = DirectoryPath.TrimEnd(Path.DirectorySeparatorChar);
      Scripting.FileSystemObject fso = new Scripting.FileSystemObjectClass();
      // check if folder exists, if yes - no work to do
      if(!fso.FolderExists(DirectoryPath))
      {
          int i = DirectoryPath.LastIndexOf(Path.DirectorySeparatorChar);
          // find last\lowest folder name
          string CurrentDirectoryName = DirectoryPath.Substring(i+1, DirectoryPath.Length-i-1);
          // find parent folder of the last folder
          string ParentDirectoryPath = DirectoryPath.Substring(0,i);
          // recursive calling of function to create all parent folders 
          CreateDirectory(ParentDirectoryPath);
          // create last folder in current path
          Scripting.Folder folder = fso.GetFolder(ParentDirectoryPath);
          folder.SubFolders.Add(CurrentDirectoryName);
      }
  }

Rate This Article

How useful was this article?

Not useful A little useful Useful Very useful Everything I needed