Free Web Development Online Tutorials, Learn to Code
Directory in C#, Learn C# programming Language, Free C# Tutorial for Beginners

Directory in C#, System.IO.Directory, DirectoryInfo

In this article you will learn about how to work with directories in C# .Net

Directory and DirectoryInfo in C# is a static class, comes under System.IO namespace, provides functionality for creating, moving, deleting and accessing subdirectories in C# .Net

Create Directory in C#

Using Directory.CreateDirectory() we can create directory within the web application, the function has following two overload

Directory.CreateDirectory(virtual path), the following code will create a new directory called "new-directory" in root of your web application.

string _virtualPath=Server.MapPath("~/new-directory");

Another overload is System.IO.Directory.CreateDirectory(virtual-path,DirectoryObjectSecurity), this allow you to set directory security.

string _virtualPath=Server.MapPath("~/new-directory");
System.Security.AccessControl.DirectoryObjectSecurity _security=;//(to be implemented) System.IO.Directory.CreateDirectory(_virtualPath,_security);

Delete Directory in C# .Net

We can delete any directory within our web application using static delete method of System.IO.Directory, let's take a look at the example below.

string _virtualPath=Server.MapPath("~/new-directory");
// if recursive=true, then it will delete all sub-directories and files in it.

Move Directory in C# .Net

Move a directory from one location to another location within your web application.
string _virtualPath = Server.MapPath("~/new-directory");
string _virtualPathDestination = Server.MapPath("~/new-directory-2018)");
System.IO.Directory.Move(_virtualPath, _virtualPathDestination);

Another often useful method is to check if directory Exists can be checked this way System.IO.Directory.Exists(_virtualPath)

System.IO.Directory also can get the details of all subdirectories, files in it in form of string array and parent DirectoryInfo DirectoryInfo _directoryinfo= System.IO.Directory.GetParent(_virtualPath);, Now again "_directoryinfo" can get the details of all directory inside it, also the current directory info.

In this context you should also learn FileInfo Class in C#