0

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!

4
  • 1
    BTW Doesn't the desktop folder always exist anyway? Commented Mar 1, 2016 at 19:48
  • 2
    This code won't create a directory anyway, as when it's fixed as indicated by @Ashkan, it'll try to create the Desktop directory, which already exists... Commented Mar 1, 2016 at 19:49
  • Why is it saying "If directory exists, create it"? Commented Mar 1, 2016 at 19:51
  • If you wish to create a directory on your desktop, then just combine the Desktop directory with your intended directory name (using Path.Combine method: msdn.microsoft.com/en-us/library/fyy7a5kt%28v=vs.110%29.aspx). But you should only create that directory if it doesn't already exist, rather than if it does. And don't try to create the Desktop directory. Commented Mar 1, 2016 at 20:14

2 Answers 2

2

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); 
            }
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

You could just call Directory.CreateDirectory, because this code will internally check if the directory is existing or not.
1

Use Enviorment.SpecialFolder.DesktopDirectory instead, the Enviorment.SpecialFolder.Desktop enumeration is a virtual folder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.