How do I create a function that loops through folders to see if a folder exists and create a new folder?

Posted on 2012-08-22
Last Modified: 2012-08-27
Hello.  So here is what I need.  I need a function that accepts a folder path like, "C:\users\myuser" and checks to see if that folder exists and if it does exist it needs to append a "1" to the end of 'myuser' and continue to check if the appended folder name exists until it finds a folder that does NOT exist and return that folder path.  I may have "myuser1" and "myuser2" existing but "myuser3" is available.  so i would need my function to return that path to my main function so it could create the folder and move on with it's other operations.

basically i have a main function that does a lot of operations and one part of the operation is to call a function that checks if a folder name is available for creation.

anyone help with that?

Question by:linuxrox
    LVL 2

    Assisted Solution

    Might be buggy. Don't have an IDE

    Function folderExists(fld as string) as string
    fld = fld.tolower.trim(New Char() {"\"}) 'get rid of trailing slash because you need to check if file exists
    dim fso = createobject("scripting.filesystemobject")
    if not fso.folderexists(fld) andalso not fso.fileexists(fld) return fld
    dim prnFld 
    if fso.folderexists(fld) then
       prnFld = fso.getfolder(fld).parentfolder
       prnFld = fso.getfile(fld).parentfolder
    end if
    dim maxFld = 0
    for each sFld in prnFld.subfolders
    if left(sfld.path, len(fld)).tolower() = fld and IsNumeric(mid(sfld.path, len(fld), 1000)) then 
       dim num = val(mid(sfld.path, len(fld), 1000))
       if num > maxfld then maxfld = num
    end if
    for each sFld in prnFld.files
    if left(sfld.path, len(fld)).tolower() = fld and IsNumeric(mid(sfld.path, len(fld), 1000)) then 
       dim num = val(mid(sfld.path, len(fld), 1000))
       if num > maxfld then maxfld = num
    end if
    fso.move(fld, fld & maxfld)
    return  fld & (maxfld + 1)
    end function

    Open in new window

    LVL 40

    Assisted Solution

    by:Jacques Bourgeois (James Burger)
    Babelos did provide something that works, but this code uses classes created for VBScript / VBA, not .NET.

    For performance, maintenance, scalability and most important, simply because they offer a lot more possibilities, you should use .NET classes as much as possible.

    .NET has classes that do a lot more than the old Scripting library to work with drives, directories and files. Here is how I would approach it in purely .NET code.
    Dim baseName As String = "C:\users\myuser"
    'You did not say what you wanted to do C:\users\myuser did not exist,
    'so I assume that you want to create it
    If Not System.IO.Directory.Exists(baseName) Then
    	For index As Integer = 1 To 100	'Replace 100 by the highest number or directories you are ready to accept
    		If Not System.IO.Directory.Exists(baseName & index) Then
    			System.IO.Directory.CreateDirectory("C:\users\myuser" & index)
    		End If
    End If

    Open in new window


    Accepted Solution

    here's what i came up with guys....this works perfectly
    create "c:\folder" and "c:\folder1" and "c:\folder2" on your drive and run this.  

    Imports System
    Imports System.IO
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Dim folder As String = ""
            Dim x As Integer = -1
            Dim found As Boolean = False
                x = x + 1
                If x = 0 Then
                    folder = "c:\folder"
                    folder = "c:\folder" & x
                End If
                found = checkfolder(folder, x)
            Loop Until found = True
        End Sub
    Private Function checkfolder(ByVal folder As String, ByVal x As Integer) As Boolean
            If Directory.Exists(folder) Then
                checkfolder = False
                checkfolder = True
                Return checkfolder
            End If
        End Function

    Open in new window

    LVL 2

    Expert Comment

    James, 2 comments:

    1) You don't check if file exists. You can't name a directory the same as a file. And because you need to check files as well, you need to get rid of the trailing slash.

    2) Author wants the directory path string, not the directory.

    Linuxrox: your solution also has the first problem.

    Author Comment

    Baleboos:  There are no files in the root folder where the folders are being created so there is no need to check for existing files with the same name.  these are basically home folders for users in active directory and they are all created on a main root drive for which no files exist.

    Author Closing Comment

    This was exactly what I was trying to achieve.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Join & Write a Comment

    If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
    Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now