Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Checking if string path is valid [modified]

Checking if string path is valid [modified]

Scheduled Pinned Locked Moved C#
performancehelptutorialquestion
18 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A AspDotNetDev

    Ah, so you just want to see if a hypothetical path (which may or may not already exist on the file system) is valid as far as the characters it uses and length and such? In that case, you have two options. Option 1 would be to use this code and catch exceptions for invalid characters and such (various types of exceptions will be thrown based on how the path is invalid):

    // These will throw exceptions.
    DirectoryInfo di = new DirectoryInfo("***");
    FileInfo fi = new FileInfo("***");

    The other option is to check this manually. Some things to consider when creating this code: Path.AltDirectorySeparatorChar Path.DirectorySeparatorChar Path.GetInvalidFileNameChars() Path.GetInvalidPathChars() Check if root drives exist (may not apply to network paths) Avoid known bad folder names (e.g., COM or something like that is invalid because it is reserved). Path.VolumeSeparatorChar Maximum path length (260 characters?) and max filename length. If the path does exist, then it must be valid (but determining if it is invalid will take more work).

    [Forum Guidelines]

    S Offline
    S Offline
    Saksida Bojan
    wrote on last edited by
    #7

    Thank for your reply. It seems it is easiest to do is use Directory.CreateDirectory() and see if it can create. That Path class has some interesting methods.

    1 Reply Last reply
    0
    • S Saksida Bojan

      I have created a check that if path exsist by creating and removing temporary folder. Is there any better check to check if a path inside string is valid? Edit: Rephased Edit 2: More Info I used like This: (From Memory) String path = "c:\TempCacheFolder";

      Directory.CreateDirectory(path);
      Directory.RemoveDirectory(path);

      I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

      modified on Saturday, March 6, 2010 9:32 AM

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #8

      I just use a FileInfo. Don't try to write your own.

      S 1 Reply Last reply
      0
      • S Saksida Bojan

        I have created a check that if path exsist by creating and removing temporary folder. Is there any better check to check if a path inside string is valid? Edit: Rephased Edit 2: More Info I used like This: (From Memory) String path = "c:\TempCacheFolder";

        Directory.CreateDirectory(path);
        Directory.RemoveDirectory(path);

        I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

        modified on Saturday, March 6, 2010 9:32 AM

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #9

        Saksida Bojan wrote:

        Is there any better check to check if a path inside string is valid?

        Building on the former posts, you'd like to check whether the parent-path is valid, and whether the name-part of the new folder is valid?

        C:\Windows\MyBla:Folder

        In order to verify whether "MyBla:Folder" is a valid name? You could check the parent-path as suggested, but there may be a *lot* more reasons why the creation of a folder might fail. Don't forget your try-except :)

        I are Troll :suss:

        S 1 Reply Last reply
        0
        • P PIEBALDconsult

          I just use a FileInfo. Don't try to write your own.

          S Offline
          S Offline
          Saksida Bojan
          wrote on last edited by
          #10

          Nope. FileInfo is not what I wanted. I asked about Directory not file. I used like This: (From Memory) String path = "c:\TempCacheFolder";

          Directory.CreateDirectory(path);
          Directory.RemoveDirectory(path);

          I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

          P 1 Reply Last reply
          0
          • L Lost User

            Saksida Bojan wrote:

            Is there any better check to check if a path inside string is valid?

            Building on the former posts, you'd like to check whether the parent-path is valid, and whether the name-part of the new folder is valid?

            C:\Windows\MyBla:Folder

            In order to verify whether "MyBla:Folder" is a valid name? You could check the parent-path as suggested, but there may be a *lot* more reasons why the creation of a folder might fail. Don't forget your try-except :)

            I are Troll :suss:

            S Offline
            S Offline
            Saksida Bojan
            wrote on last edited by
            #11

            I used like This: (From Memory) String path = "c:\TempCacheFolder";

            Directory.CreateDirectory(path);
            Directory.RemoveDirectory(path);

            I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

            Eddy Vluggen wrote:

            In order to verify whether "MyBla:Folder" is a valid name?

            More like if it can create without creating new folder. I am designing custom control (Currently Cache Engine) I intend to handle it without trusting user input. And return errors that the user (developer) can easily repair problem

            1 Reply Last reply
            0
            • S Saksida Bojan

              John Simmons / outlaw programmer wrote:

              I don't understand. You mean the string itself might be empty/null?

              Might be. It could lead to an invalid folder like on Storage devices when removed. The folder itself doesn't have to exsist. Like temporary folder, where cache is placed. In other obvious errors, like invalid chars.

              realJSOPR Offline
              realJSOPR Offline
              realJSOP
              wrote on last edited by
              #12

              I suggest that you write a console app and play around with it. You seem to be aware of everything that coudl be wrong with a path name, so see what the DirectoryExists() method does with the various invalid possibilities. You could have figured all that out on your own by now... Be a programmer, fer christ's sake.

              .45 ACP - because shooting twice is just silly
              -----
              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

              S 1 Reply Last reply
              0
              • realJSOPR realJSOP

                I suggest that you write a console app and play around with it. You seem to be aware of everything that coudl be wrong with a path name, so see what the DirectoryExists() method does with the various invalid possibilities. You could have figured all that out on your own by now... Be a programmer, fer christ's sake.

                .45 ACP - because shooting twice is just silly
                -----
                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                S Offline
                S Offline
                Saksida Bojan
                wrote on last edited by
                #13

                Thanks for the info. It seems i would need to create my own parser. Thanks for everyone for their commets.

                1 Reply Last reply
                0
                • S Saksida Bojan

                  I have created a check that if path exsist by creating and removing temporary folder. Is there any better check to check if a path inside string is valid? Edit: Rephased Edit 2: More Info I used like This: (From Memory) String path = "c:\TempCacheFolder";

                  Directory.CreateDirectory(path);
                  Directory.RemoveDirectory(path);

                  I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

                  modified on Saturday, March 6, 2010 9:32 AM

                  L Offline
                  L Offline
                  Luc Pattyn
                  wrote on last edited by
                  #14

                  In order to determine validity of a path, you should not modify the file system, hence CreateDirectory and RemoveDirectory are not acceptable. Calling them may cause a lot of unwanted side effects, e.g. when a FileSystemWatcher has been installed. What you can do is: 1. use Path.GetFullPath() 2. use new DirectoryInfo() each of those will throw an appropriate exception when the path isn't valid. And of course you could parse the path yourself (not recommended). :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                  I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


                  S 1 Reply Last reply
                  0
                  • S Saksida Bojan

                    I have created a check that if path exsist by creating and removing temporary folder. Is there any better check to check if a path inside string is valid? Edit: Rephased Edit 2: More Info I used like This: (From Memory) String path = "c:\TempCacheFolder";

                    Directory.CreateDirectory(path);
                    Directory.RemoveDirectory(path);

                    I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

                    modified on Saturday, March 6, 2010 9:32 AM

                    R Offline
                    R Offline
                    RichardM1
                    wrote on last edited by
                    #15

                    I have to agree with the other posters, creating and deleting the dir is at best inelegant. You may have a valid path, with write permission, but not create permission. Worst case, I would check it for null, then get info on it from Directory. If this fails, get rid of everything from the last '/' back, inclusive, and try again. If that fails you know the proposed directory/file does not exist and that the directory holding also does not exist. If it succeeds, you would have needed to get file info to determine if you have write or create permissions to the paths given. We had a sergeant, in officer basic course, when (not if)one of us LTs came with an f'd up way to do something, he'd say: "it's a technique"

                    Opacity, the new Transparency.

                    1 Reply Last reply
                    0
                    • S Saksida Bojan

                      I have created a check that if path exsist by creating and removing temporary folder. Is there any better check to check if a path inside string is valid? Edit: Rephased Edit 2: More Info I used like This: (From Memory) String path = "c:\TempCacheFolder";

                      Directory.CreateDirectory(path);
                      Directory.RemoveDirectory(path);

                      I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

                      modified on Saturday, March 6, 2010 9:32 AM

                      G Offline
                      G Offline
                      Giorgi Dalakishvili
                      wrote on last edited by
                      #16

                      You can do it with NDepend.Helpers.FileDirectoryPath[^] library

                      Giorgi Dalakishvili #region signature My Articles Browsing xkcd in a windows 7 way[^] #endregion

                      1 Reply Last reply
                      0
                      • L Luc Pattyn

                        In order to determine validity of a path, you should not modify the file system, hence CreateDirectory and RemoveDirectory are not acceptable. Calling them may cause a lot of unwanted side effects, e.g. when a FileSystemWatcher has been installed. What you can do is: 1. use Path.GetFullPath() 2. use new DirectoryInfo() each of those will throw an appropriate exception when the path isn't valid. And of course you could parse the path yourself (not recommended). :)

                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                        I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.


                        S Offline
                        S Offline
                        Saksida Bojan
                        wrote on last edited by
                        #17

                        tham. Didn't know DirecotryInfo had such flexebility. thanks. The code so far:

                          public static bool IsValidPath(String path)
                            {
                                DirectoryInfo di;
                        
                                // Atempt to put String path into DirectoryInfo
                                try
                                {
                                    di = new DirectoryInfo(path);
                                }
                                catch (NotSupportedException) { return false; }
                        
                                // It must be logical drive. (HDD, SSD or USB Mass Storage)
                                bool foundLogicalDrive = false;
                                foreach (String str in Directory.GetLogicalDrives())
                                {
                                    if (path.Substring(0, 3).ToUpper() == str)
                                        foundLogicalDrive = true;
                                }
                                
                                if (!foundLogicalDrive)
                                    return false;
                        
                                return IsValidPathParser(di);
                               
                            }
                        
                            private static bool IsValidPathParser(DirectoryInfo di)
                            {
                                if (di.Exists)
                                {
                                    // ACL checks here
                                    return true;
                                }
                                else
                                {
                                    if (di.Name.ToUpper() != di.Root.Name.ToUpper())
                                        return IsValidPathParser(di.Parent);
                                    else
                                        return false;
                                }
                            }
                        

                        The last part i wan't to check if users have permision to create and write in that folder. So far i haven't found anything usefull. Still googleing about DirectorySecurty.

                        1 Reply Last reply
                        0
                        • S Saksida Bojan

                          Nope. FileInfo is not what I wanted. I asked about Directory not file. I used like This: (From Memory) String path = "c:\TempCacheFolder";

                          Directory.CreateDirectory(path);
                          Directory.RemoveDirectory(path);

                          I needed to know if imputed string is valid before creating. I am currently designing Cache Engine for my custom control. The property CacheFilePath has get and set property. When someone programaticly enter an invalid area where it can't be written, without actually creating it before it is needed. And there is error within my approach. If I create directory with a path that have more subfolder that doesn't exsist: Example: Faze1. Test Create a folder. C:\MyApp\UnkownFolder\Unkownfolder2\TempImageCache. Faze2. Remove Folder. (Will remove only TempImageCache) I wan't to avoid this needless step. I only wan't to validate, that the unknown directory can be created without actually creating before needing. I am sorry if I was too cryptic about my previous posts

                          P Offline
                          P Offline
                          PIEBALDconsult
                          wrote on last edited by
                          #18

                          Saksida Bojan wrote:

                          if imputed string is valid before creating

                          That's a waste of time -- things can change between the test and the creation. When it comes time to create, just try to create and report any errors.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups