Search code examples
c#system.io.directory

Code not creating directories


I'm trying to write a folder to the desktop. So far, I've gotten to this point. I initialize the method like this:

 public class Initialize 
        {
            public static void Main () 
            {
                Folder.CreateFolder();
            }
        }

And it takes the code from here:

public class Folder
    {
        public static void CreateFolder()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //Gets desktop folder
            if(System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path); 
            }
        }
    }

I'm thinking part of my problem is in the CreateDirectory call, but I'm not sure. All I know is only a terminal pops up, and no folder is created. Can anyone see the error? Let me know, thanks in advance!


Solution

  • You must Try to create folder if it does not exist and also use Environment.SpecialFolder.DesktopDirectory instead of Environment.SpecialFolder.Desktop

    Add ! to your comparison

    public class Folder
        {
            public static void CreateFolder()
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); //Gets desktop folder
                if(!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path); 
                }
            }
        }