[RESOLVED] [2005] Validating Path-VBForums
Results 1 to 33 of 33

Thread: [RESOLVED] [2005] Validating Path

  1. #1

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Resolved [RESOLVED] [2005] Validating Path

    The user enters a path name into a textbox. I need to make sure this path name is valid, whether it exists or not.

    The function System.IO.Path.GetInvalidFileNameChars() doesn't help with this because according to it, the colon ( is an allowable character. Unfortunately it isn't a universally allowable character.

    That is: 'C:\MyFolder' is a valid folder name. However 'C:\My:Folder" is not.

    While I could write code to detect for a colon in any position except character 1 in the textbox text, that seems very VB version 4. I would think that the Microsoft crew would anticipate something like this and have a built in class.

    Is there one? System.IO doesn't appear to have one and this is where the Path object lives.

    Anyone???

  2. #2
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,745

    Re: [2005] Validating Path

    vb Code:
    1. '2005 Only
    2. If My.Computer.FileSystem.DirectoryExists("Directory here") Then
    3.     'do stuff
    4. End If
    5.  
    6.    'OR
    7.  
    8. If IO.Directory.Exists("Directory here") Then
    9.     'do stuff
    10. End If
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  3. #3

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Thank you. But the directory doesn't HAVE to exist at this point. The app will automatically create the directory later, if need be. I need to notify the user (preferably in the Text_Change event) that the path entered/changed is invalid.

    If 'C:\MyFolder' is the original content of the textbox, the folder is valid.
    If the user changes the text to 'C:\MyFQolder' that is valid also.
    If the user changes the text to 'C:\My:Folder', that is not valid, and I want to tell them right then.

    I hope that clarifies the problem.
    Last edited by rjbudz; Oct 5th, 2007 at 02:16 PM.

  4. #4
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,745

    Re: [2005] Validating Path

    Could you perhaps use an Folder Browser Dialog instead, and when they select the folder from that, simply put the result into a textbox (making it a read only text box or whatever).

    That way it will handle all the validation for you. It seems the easiest way than trying to validate a folder path in a text box that might not even exist.
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  5. #5

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Even though it would be a lot easier to check for an existing folder, or allowing the user to select an existing folder, that's not how the software is going to work. I didn't get to write the spec.

    The user can enter a folder name. If what they entered is a valid folder name (whether it currently exists or not!), the software creates it or accepts it, respectively.

    If not, it tells the user about it.

  6. #6
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,745

    Re: [2005] Validating Path

    This is a horrible way of doing it but could you put the Folder in a try/catch block and simply catch any errors and alert them to the fact. It's completely barmy though
    vb Code:
    1. Try
    2.       IO.Directory.CreateDirectory(Me.TextBox1.Text)
    3.  
    4.    Catch ex As Exception
    5.  
    6.        MessageBox.Show("The folder path you entered is not valid, try again", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
    7.         Me.TextBox1.Select()
    8.  
    9. End Try
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  7. #7
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    30,844

    Re: [2005] Validating Path

    Quote Originally Posted by rjbudz
    Even though it would be a lot easier to check for an existing folder, or allowing the user to select an existing folder, that's not how the software is going to work. I didn't get to write the spec.

    The user can enter a folder name. If what they entered is a valid folder name (whether it currently exists or not!), the software creates it or accepts it, respectively.

    If not, it tells the user about it.
    Specs should be able to be changed.... nothing is ever permanently set in stone... that's why we have Change Orders.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    I'm sorry, but you're telling me that because it's difficult to program this, then I should ask to change the specs?

    I could just see the look on the face of my supervisor when I tell her we need to change the specs because it's too hard to do. I know what she would say:

    lol.

    Seriously though, I really thought Microsoft would anticipate this and come up with something to do it. They have thousands of classes available. How did this one get by them?

    stimbo, I had thought of doing that, then deleting the directory afterward. Kind of kludge (RELLY kludge, actually! ), and I don't like to run into stuff like that when I'm doing maintenance, so I can't, in good conscience, do it.

    But it would work. Thanks.

    So, the answer, as I stated in the original post, will have to be to test for the colon in a substring for char position 0 and for all positions after position 1.

    Not to change the specs.

    I just figured if I'm going to code in .NET, I should take advantage of all it's functionality.

    That's what I get for trying to be eloquent, I guess. So much for 'improved'!

    I'm still convinced that they have something to do this. It's GOT to be a somewhat frequent situation. Anyone????
    Last edited by rjbudz; Oct 11th, 2007 at 12:03 PM.

  9. #9
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,745

    Re: [2005] Validating Path

    I'm sorry, but you're telling me that because it's difficult to program this, then I should ask to change the specs?
    No, we are telling you to change the specs because there are better ways, they easily exist and you won't or rather the ridiculous specs you have been given won't allow them to be used.

    I really thought Microsoft would anticipate this and come up with something to do it.
    They have - it's the FolderBrowserDialog

    You are artificially creating a scenario that shouldn't be really used because of the massive risk or error that it generates. If so, I doubt they would just check for ":" and simply catch any error that could arise.

    I just figured if I'm going to code in .NET, I should take advantage of all it's functionality.
    Same as the point above - use the FolderBrowserDialog

    If you want to check each character in the textbox field then you could do this but this still wouldn't be correct, I can see other errors that could happen...

    Code:
    Dim myChar() As Char = CType(Me.TextBox1.Text, Char())
    
    If myChar.Length > 2 Then
        For i As Integer = 2 To myChar.Length - 1
            If myChar(i) = ":" Then
                MessageBox.Show("Stop putting illegal characters in")
                Exit Sub
            End If
       Next
    
    End If
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  10. #10
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    30,844

    Re: [2005] Validating Path

    Plus the FolderBrowser is easier for users to use.... any time I have to type in an address like that... I fire up File Explorer, browse out to the fodler I want, copy the address and paste it where it needs to go.... anything that's more than one level deep is too much for me....

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  11. #11

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Displaying an editable textbox with a preset directory path (such as 'C:\Program Files\YourNewProgram' is so common with software installation that error checking for an invalid path should be a no-brainer to include.

    My thought, anyway. I guess I'm wrong, huh?

  12. #12
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,745

    Re: [2005] Validating Path

    Then they would generally put the whole thing in a try/catch block as mentioned in post #6 or a mixture of validating methods. Generally not what you are trying to do.
    Last edited by stimbo; Oct 11th, 2007 at 12:16 PM.
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  13. #13

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    I've already resigned myself to go the substring method, but just so you guys understand why the spec is laid out as it is:

    The user initiates a file transfer. This is a bunch of files that have been updated or created by said user. The files are programmatically zipped up for transfer to a server (to minimize bandwidth) where they become automatically available for all the other users that need this update.

    Part of the zip process is to select or create a directory predetermined by the original user (so the unzipping process will put the files in the correct place). Since these files generally go into a not-yet-created directory, the user gets to change the suggested one to anything he/she wants.

    Hence the need for error checking.

    Thanks, guys, for attempting to help.

  14. #14
    Fanatic Member TokersBall_CDXX's Avatar
    Join Date
    Mar 2003
    Location
    America
    Posts
    571

    Re: [2005] Validating Path

    VB Code:
    1. Function ValidPath (ByVal ThePath As String) As Boolean
    2. Try
    3. System.IO.Path.GetDirectoryName (ThePath)
    4. Return True
    5. Catch
    6. Return False
    7. End Try
    8. End Function
    Build your own personalized flash based chat room for your webpage for FREE! http://www.4computerheaven.com

  15. #15

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    ? System.IO.Path.GetDirectoryName("C:\build")
    returns: "C:\"

    ? System.IO.Path.GetDirectoryName("C:\build\some")
    returns:
    "C:\build"

    ? System.IO.Path.GetDirectoryName("C:\bu:ild\some")
    returns:
    "C:\bu:ild"

    Unfortunately, the last doesn't cause an error, so the function will return True.

    ? System.IO.Path.GetDirectoryName("C:\build\so>me")
    does error out, because it contains an invalid character for a directory name.

    But, again, the colon ':' IS valid, just not anywhere except the second character in the string.

  16. #16
    Fanatic Member bgmacaw's Avatar
    Join Date
    Mar 2007
    Location
    Atlanta, GA USA
    Posts
    524

    Re: [2005] Validating Path

    Here's one to try to see if it will work for you

    Code:
    If IO.Path.IsPathRooted(newPath) Then

  17. #17
    Addicted Member
    Join Date
    May 2006
    Location
    Manchester, England
    Posts
    255

    Re: [2005] Validating Path

    I'd be tempted to follow the spec - but as a "free of charge enhancement", put a button next to the TextBox to allow you to open the folder browser dialog, and once the user has chosen their folder, populate the TextBox with the result of the browser dialog .... and also use Stimbo's suggestion at post #6.
    At home - VB.NET 2005/2008 Express, Visual Web Developer 2005 Express
    At work - VS 2008 Standard (VB)
    .NET 2.0/3.5


    Visual Studio Express Learning Centre | How do I videos | MSDN VB Express Forum | MSDN VB Developer Centre

  18. #18

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Quote Originally Posted by bgmacaw
    Code:
    If IO.Path.IsPathRooted(newPath) Then
    Same situation. The common problem for all the methods cited is that the colon is recognized as a valid character for the path.

    And it IS valid. But only as the second character.

    And thanks, penguin. She's more likely to go for that than the other one!

  19. #19
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: [2005] Validating Path

    I think that you should use stimbo’s example in post #6. This way you would identify if the path is invalid or not. Note the user may have some other invalid characters in the path and this method will catch it. There is nothing horrible about this method and it is more efficient since it will do one instruction; create a folder. If it doesn’t succeed than caches the error so that you can notify the user if the path is entered is invalid.

    Although the other solution that was mentioned above posts (using FolderBrowserDialog) would be the best, since the .Net will deal with the validation of the path. But if it can be used in your project.

  20. #20

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    The code in Post 6 will actually work. The folder does not have to exist on the initial user's machine however. So I will have to delete the folder one I create it.

    You are quite right, DT, that the code also eliminates the need for other error checking.

    But, as I expected (and see it myself) the powers that be think it lacks professionalisms, so I'll go the other less straight forward route.

    Mind you, I'm not taking away from it. It will work just fine!
    Last edited by rjbudz; Oct 11th, 2007 at 04:20 PM.

  21. #21
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    30,844

    Re: [2005] Validating Path

    Quote Originally Posted by rjbudz
    I've already resigned myself to go the substring method, but just so you guys understand why the spec is laid out as it is:

    The user initiates a file transfer. This is a bunch of files that have been updated or created by said user. The files are programmatically zipped up for transfer to a server (to minimize bandwidth) where they become automatically available for all the other users that need this update.

    Part of the zip process is to select or create a directory predetermined by the original user (so the unzipping process will put the files in the correct place). Since these files generally go into a not-yet-created directory, the user gets to change the suggested one to anything he/she wants.

    Hence the need for error checking.

    Thanks, guys, for attempting to help.
    Please note: it says nothing about allowing the user to type in the folder... just that they can CHANGE it. But hey, it's your project. Just offering up ideas.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  22. #22
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: [2005] Validating Path

    So I will have to delete the folder one I create it.
    Why do you want to delete the created/exiting folder?

  23. #23

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    techgnome, don't get me wrong. I very much appreciate everyone's input, and the diligence shown it trying to resolve the issue!

    The post you quoted is the actual program as laid out by my predecessor. As such, the user can type into the textbox anything they want (though a suggested folder name is presented.

  24. #24

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    DT,

    Because the folder isn't for the user typing it in, but for the recipient's machine when they unzip the update (see post 13).

  25. #25
    Fanatic Member bgmacaw's Avatar
    Join Date
    Mar 2007
    Location
    Atlanta, GA USA
    Posts
    524

    Re: [2005] Validating Path

    OK, try this.

    Code:
        Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
            Try
                Dim PathPattern As String = "^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$"
                If System.Text.RegularExpressions.Regex.IsMatch(TextBox1.Text, PathPattern) Then
                    Debug.Print("True")
                Else
                    Debug.Print("False")
                End If
            Catch ex As Exception
                Debug.Print("Exception")
            End Try
        End Sub

  26. #26
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: [2005] Validating Path

    Quote Originally Posted by rjbudz
    DT,

    Because the folder isn't for the user typing it in, but for the recipient's machine when they unzip the update (see post 13).
    Ok that is fine!

    It is your project and you know it better. Saying that I still think that there is nothing unprofessional of using the example in post #6. Actuality I do see disadvantage of any other solutions in sense that they will deal with string manipulations that take a lot of spu time and more instructions of creating string objects, reassigning etc.

  27. #27

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Yep. I agree. It does cover all the bases regarding checking a path, because if it can't create it, then it's invalid. And it's clean, terse and easy to understand.

    I'm sure those that follow can utilize it.

    I was looking for the .NET class that addressed the issue, but am disappointed that it doesn't exist (one of you guys would have known about it if it does, I'm sure).

  28. #28
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,218

    Re: [2005] Validating Path

    bgmacaw's post using RegEx was the first thing I thought of when reading this topic.

    Regex was made to cover specific things scenario's like this one. You have a need to check a string to see if it follows the windows file system path pattern. All you need to do is know what that pattern is, which is a letter followed by a colon then a backslash followed by alphanumeric characters and a slash and so on

    That's a really easy pattern, and regex will match your string against that pattern returning a True or a False.
    Currently using: VS 2015 Enterprise on Win7 Ultimate x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  29. #29
    Fanatic Member TokersBall_CDXX's Avatar
    Join Date
    Mar 2003
    Location
    America
    Posts
    571

    Re: [2005] Validating Path

    hmm

    how about...
    VB Code:
    1. Function ValidPath(ByVal ThePath As String) As Boolean
    2.         Try
    3.             If System.IO.Path.GetFullPath(ThePath) = "" Then
    4.                 Return False
    5.             End If
    6.             Return True
    7.         Catch
    8.             Return False
    9.         End Try
    10.     End Function
    Build your own personalized flash based chat room for your webpage for FREE! http://www.4computerheaven.com

  30. #30
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    30,844

    Re: [2005] Validating Path

    Tokers - that only works if the path already exists... what if it doesn't?
    Stimbo - that works for creating it.... what if the user then cancels? The directory is then left out there, empty.

    The regEx solution posted is probably about as ideal as it's going to get.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  31. #31
    Fanatic Member TokersBall_CDXX's Avatar
    Join Date
    Mar 2003
    Location
    America
    Posts
    571

    Re: [2005] Validating Path

    Tech,

    when i test it works even when the directory does not exist.
    Build your own personalized flash based chat room for your webpage for FREE! http://www.4computerheaven.com

  32. #32
    Addicted Member iehjsucker's Avatar
    Join Date
    Sep 2005
    Posts
    150

    Re: [2005] Validating Path

    You make your work harder.. try this one. If the path entered, wether existing or not, is valid, you'll get true if not, then false. so easy
    Code:
        Private Function ValidatePath(ByVal Path As String) As Boolean
            Try
                Dim MyPath As String
                MyPath = IO.Path.GetFullPath(Path)
                Return True
            Catch ex As Exception
                MsgBox("Path created is not valid.", MsgBoxStyle.Information, "Error")
                Return False
            End Try
        End Function





    =============
    ..code masters..

  33. #33

    Thread Starter
    Hyperactive Member rjbudz's Avatar
    Join Date
    Jul 2005
    Location
    San Diego
    Posts
    262

    Re: [2005] Validating Path

    Thanks for the great suggestions!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.