C# If a folder does not exist, create it

Just write this line :

System.IO.Directory.CreateDirectory(myDir);
  • If the folder does not exist yet, it will be created.
  • If the folder exists already, the line will be ignored.

Summary

Exposes static methods for creating, moving, and enumerating through directories and subdirectories.

Remarks

All methods of the Directory class are static and can therefore be called without having an instance of a directory. The DirectoryInfo class contains only instance methods. The static methods of the Directory class perform a security check on all methods. If you are going to reuse an object several times, consider using the corresponding instance method of DirectoryInfo instead, because the security check will not always be necessary.

Note In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, “c:\temp c:\windows” also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string.In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all of the following are acceptable paths:

  • “c:\\MyDir” in C#, or “c:\MyDir” in Visual Basic. (Visual Basic not implemented in the shared source CLI)
  • “c:\\MyDir” in C#, or “c:\MyDir” in Visual Basic. (Visual Basic not implemented in the shared source CLI)
  • “MyDir\\MySubdir” in C#, or “MyDir\MySubDir” in Visual Basic. (Visual Basic not implemented in the shared source CLI)
  • “\\\\MyServer\\MyShare” in C#, or “\\MyServer\MyShare” in Visual Basic. (Visual Basic not implemented in the shared source CLI)

By default, full read/write access to new directories is granted to all users.

 

Reference: Article about Directory.CreateDirectory at MSDN

4.5/5 - (2 votes)