In this article you will learn about how to work with directories in C# .Net
System.IO.Directory, DirectoryInfo
Class.
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
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"); System.IO.Directory.CreateDirectory(_virtualPath);
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);
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"); System.IO.Directory.Delete(_virtualPath); // if recursive=true, then it will delete all sub-directories and files in it. System.IO.Directory.Delete(_virtualPath,true);
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#