[vb.net] How do I create a folder in VB if it doesn't exist?

I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.

I want my program to download the apps to program files\any name here\

So basically I need a function that checks if a folder exists, and if it doesn't it creates it.

This question is related to vb.net installation directory

The answer is


If(Not System.IO.Directory.Exists(YourPath)) Then
    System.IO.Directory.CreateDirectory(YourPath)
End If

Under System.IO, there is a class called Directory. Do the following:

If Not Directory.Exists(path) Then
    Directory.CreateDirectory(path)
End If

It will ensure that the directory is there.


Try the System.IO.DirectoryInfo class.

The sample from MSDN:

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Since the question didn't specify .NET, this should work in VBScript or VB6.

Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
   objFSO.CreateFolder(strFolder)
End If

Try the System.IO.DirectoryInfo class.

The sample from MSDN:

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Since the question didn't specify .NET, this should work in VBScript or VB6.

Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
   objFSO.CreateFolder(strFolder)
End If

Try this: Directory.Exists(TheFolderName) and Directory.CreateDirectory(TheFolderName)

(You may need: Imports System.IO)


VB.NET? System.IO.Directory.Exists(string path)


Directory.CreateDirectory() should do it. http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx

Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:

Hope that helps.


(imports System.IO)

if Not Directory.Exists(Path) then
  Directory.CreateDirectory(Path)
end if

Directory.CreateDirectory() should do it. http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx

Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:

Hope that helps.


(imports System.IO)

if Not Directory.Exists(Path) then
  Directory.CreateDirectory(Path)
end if

If Not Directory.Exists(somePath) then
    Directory.CreateDirectory(somePath)
End If

You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.


I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.

Cheers


Just do this:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.

Hope it helps!

-nfell2009


Questions with vb.net tag:

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config Click a button programmatically Exception of type 'System.OutOfMemoryException' was thrown. how to refresh my datagridview after I add new data Fastest way to add an Item to an Array Getting Current time to display in Label. VB.net How to make String.Contains case insensitive? Display date in dd/mm/yyyy format in vb.net lists and arrays in VBA Read a file line by line with VB.NET vb.net get file names in directory? Download Excel file via AJAX MVC How to convert answer into two decimal point How to clear exisiting dropdownlist items when its content changes? how to get data from selected row from datagridview Measuring code execution time Setting focus to a textbox control How to run a Command Prompt command with Visual Basic code? How to define a Sql Server connection string to use in VB.NET? Converting string to byte array in C# Wait .5 seconds before continuing code VB.net VB.NET Connection string (Web.Config, App.Config) The name does not exist in the namespace error in XAML codes for ADD,EDIT,DELETE,SEARCH in vb2010 Removing items from a ListBox in VB.net How to convert a Date to a formatted string in VB.net? Best /Fastest way to read an Excel Sheet into a DataTable? IFrame: This content cannot be displayed in a frame How to open child forms positioned within MDI parent in VB.NET? In Visual Basic how do you create a block comment Reference to a non-shared member requires an object reference occurs when calling public sub Change the row color in DataGridView based on the quantity of a cell value Get the current date and time List(of String) or Array or ArrayList Convert string to datetime in vb.net How can I Insert data into SQL Server using VBNet Sorting a Data Table DataTable: How to get item value with row name and column name? (VB) Need help rounding to 2 decimal places Sort a List of Object in VB.NET How to programmatically add controls to a form in VB.NET

Questions with installation tag:

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) Conda version pip install -r requirements.txt --target ./lib How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" PackagesNotFoundError: The following packages are not available from current channels: Tensorflow import error: No module named 'tensorflow' Downgrade npm to an older version Create Setup/MSI installer in Visual Studio 2017 how to install tensorflow on anaconda python 3.6 Application Installation Failed in Android Studio How to install pip for Python 3.6 on Ubuntu 16.10? Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow ImportError: No module named tensorflow Unable to set default python version to python3 in ubuntu gradlew command not found? Installing TensorFlow on Windows (Python 3.6.x) How to install Visual C++ Build tools? How to install JQ on Mac by command-line? Session 'app': Error Installing APK How to Install gcc 5.3 with yum on CentOS 7.2? How to install Python packages from the tar.gz file without using pip install "pip install unroll": "python setup.py egg_info" failed with error code 1 "RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38 Can't run Curl command inside my Docker Container How to install Android SDK on Ubuntu? How to install older version of node.js on Windows? Tensorflow installation error: not a supported wheel on this platform pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory pip install failing with: OSError: [Errno 13] Permission denied on directory gcloud command not found - while installing Google Cloud SDK How to install VS2015 Community Edition offline How can I find the product GUID of an installed MSI setup? How to generate .env file for laravel? Maven Installation OSX Error Unsupported major.minor version 51.0 E: Unable to locate package mongodb-org Visual Studio 2015 installer hangs during install? Wheel file installation "installation of package 'FILE_PATH' had non-zero exit status" in R sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory Installing Python library from WHL file Installing Node.js (and npm) on Windows 10 Error:Unable to locate adb within SDK in Android Studio Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing Install IPA with iTunes 12 Error in installation a R package How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning? Pip Install not installing into correct directory? Cannot install Aptana Studio 3.6 on Windows ADB Install Fails With INSTALL_FAILED_TEST_ONLY Batch script to install MSI Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

Questions with directory tag:

Moving all files from one directory to another using Python What is the reason for the error message "System cannot find the path specified"? Get folder name of the file in Python How to rename a directory/folder on GitHub website? Change directory in Node.js command prompt Get the directory from a file path in java (android) python: get directory two levels up How to add 'libs' folder in Android Studio? How to create a directory using Ansible Troubleshooting misplaced .git directory (nothing to commit) Create a txt file using batch file in a specific folder how to include glyphicons in bootstrap 3 Iterating through directories with Python PHP - Move a file into a different folder on the server ERROR 403 in loading resources like CSS and JS in my index.php Python copy files to a new directory and rename if file name already exists How to create folder with PHP code? Get all directories within directory nodejs Portable way to check if directory exists [Windows/Linux, C] Moving up one directory in Python Correctly ignore all files recursively under a specific folder except for a specific file type Excel VBA Open a Folder Android: How to open a specific folder via Intent and show its content in a file browser? How can I extract the folder path from file path in Python? How do I find all files containing specific text on Linux? Check folder size in Bash Save file to specific folder with curl command How do I find the current directory of a batch file, and then use it for the path? Easy way to test an LDAP User's Credentials Getting current directory in VBScript How do I get a list of folders and sub folders without the files? how to zip a folder itself using java List all files in one directory PHP Node.js check if path is file or directory Java - Search for files in a directory How to push a new folder (containing other folders and files) to an existing git repo? How to list the files in current directory? Excel VBA Check if directory exists error How can I exclude multiple folders using Get-ChildItem -exclude? pros and cons between os.path.exists vs os.path.isdir Getting all file names from a folder using C# Listing only directories using ls in Bash? Method to get all files within folder and subfolders that will return a list Directory.GetFiles of certain extension Save current directory in variable using Bash? Deleting folders in python recursively Unix - copy contents of one directory to another How to get folder directory from HTML input type "file" or any other way? How to copy a file along with directory structure/path using python? Count how many files in directory PHP