CSharp .Net Tutorial: Directory Manipulation

James Cloud
Introduction

Whether you are creating a file explorer, a zip utility, or any program that needs to access folders, this guide will show you, step by step, how to rename, delete, or create new folders.

Before you can begin to make file/folder operations, however, you must make the necessary includes. Add this code to your projects 'using' section,

using System.IO;

Step One - Renaming Folders

To rename a folder using .Net framework code, create a function called 'renameFolder' with the source code given below,

private void renameFolder(String origFolder, String newFolder)
{
String tmpFolder = origFolder.Substring(0, origFolder.LastIndexOf(@"\"));
tmpFolder = tmpFolder + "\\" + newFolder;
Directory.Move(origFolder, tmpFolder);
}

Now, in order to rename a folder simply call the newly created function renameFolder passing the folder you wish to rename as the first parameter and the new desired folder name as the second parameter.

Step Two - Deleting Folders

Deleting a folder is much easier, there is really no need to create a separate function, as .Net comes with one by default. To delete a folder call the 'Directory.Delete()' method and pass the directory's path as the first parameter. There is an optional boolean second parameter which, when enabled, will delete recursively. In other words it will destroy directories, sub-directories, and files.

Step Three - Creating New Folders

Creating a folder is almost as simple, if not simpler, than deleting a folder. The .Net frameworks also include a method called 'Directory.CreateDirectory()' which will make a brand new directory using the path your specify. This function takes two parameters, the first, a string, and the second, a System.Security.AccessControl.DirectorySecurity parameter. The string parameter is the path to the new folder that you wish to create. The second parameter will allow you to control the security settings of the new folder, such as read only and other access types.

Conclusion

With the highlighted methods given in this article, you can incorporate file renaming, deletion, and creation processes into your CSharp .Net applications and projects. However, always practice caution when modifying and deleting files. Deleting system files can cause your computer to stop functioning properly.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.