0

Using

Directory _dir = Directory.CreateDirectory(path);

So how to store the object of directory in a variable so then I have to check whether the directory at specified path exists or not as?

if(!_dir.exists())
{
    _dir.CreateDirectory(path);
}

Is it allowed in C#?

4
  • 2
    Directory.CreateDirectory will actually check if the directory exists before attempting to create it, so there's really no reason to check if it exists before calling it. However you can always use the DirectoryInfo class, which Directory.CreateDirectory returns, to do what you want. Commented May 23, 2016 at 16:56
  • Just fyi you will always have a race condition when writing IO code like that - be ready to catch the exogenous IO exception. blogs.msdn.microsoft.com/ericlippert/2008/09/10/… Commented May 23, 2016 at 16:58
  • @juharr it means there is no need to check whether directory exists or not because CreateDirecotory() automatically checks this. Thanks Commented May 23, 2016 at 17:01
  • "Is it allowed in C#?" the correct way it would be "if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); }" but as @juharr mentioned, CreateDirectory already verify if it exists Commented May 23, 2016 at 17:01

2 Answers 2

2

Try This...

        string path=@"C:\Users\v\Desktop\DESKTOP";
        if(!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
Sign up to request clarification or add additional context in comments.

Comments

0
DirectoryInfo dir = Directory.CreateDirectory(path);
if(!dir.Exists)
{
    dir.CreateDirectory(path);
}

Or

DirectoryInfo dir = Directory.CreateDirectory(path);
if(!Directory.Exists(path))
{
    dir.CreateDirectory(path);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.