SoFunction
Updated on 2025-04-29

C# determines whether the folder exists, and performs deletion and creation operation methods

C# determines whether the folder exists and performs deletion and creation operations

useIn namespaceDirectoryClass to delete local folders and all their contents, or create new folders when they do not exist.

1. Determine whether the folder exists, if it does not exist, create a new folder.

The parameter 'folderParh' is the full path of the incoming folder.

        // Create a new folder        private void isExists(string folderPath)
        { 
            try
            {
                // Determine whether the folder exists                if (!(folderPath))
                {
                    // If the folder does not exist, create a folder                    (folderPath);
                    ("The folder does not exist and has been created successfully.");
                }
                else
                {
                    ("The folder already exists.");
                }
            }
            catch (Exception ex)
            {
                //Catch and handle exceptions                ("An error occurred while operating the folder: " + );
            }
        }

2. Determine whether the folder exists, and delete the folder if it exists

       //Delete the folder        private void delFile(string folderPath )
        { 
            try
            {
                // Check if the folder exists                if ((folderPath))
                {
                    // Delete the folder and all its contents                    (folderPath, true);
                    ("The folder and its contents have been deleted successfully.");
                }
                else
                {
                    ("The specified folder does not exist.");
                }
            }
            catch (Exception ex)
            {
                //Catch and handle exceptions                ("An error occurred while deleting a folder: " + );
            }
        }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.