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. How to check a string to see if it’s valid for use in creating a file name

How to check a string to see if it’s valid for use in creating a file name

Scheduled Pinned Locked Moved C#
c++tutorialquestion
10 Posts 5 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.
  • E Offline
    E Offline
    earlgraham
    wrote on last edited by
    #1

    In my old c++ days, I would use my old function below; BOOL IsValidFilename(const char *szFilename) { if ( (!szFilename) || (!strlen(szFilename)) ) return (FALSE); if ( (strchr(szFilename, '.')) || (strchr(szFilename, '\\')) || (strchr(szFilename, '/')) || (strchr(szFilename, ':')) || (strchr(szFilename, '<')) || (strchr(szFilename, '>')) || (strchr(szFilename, '*')) || (strchr(szFilename, '?')) || (strchr(szFilename, '|')) || (strchr(szFilename, '\"')) ) return (FALSE); return (TRUE); } I thought there might be a cleaner way to test a string before I used it for a file name.

    Programmer Glenn Earl Graham Austin, TX

    B P 3 Replies Last reply
    0
    • E earlgraham

      In my old c++ days, I would use my old function below; BOOL IsValidFilename(const char *szFilename) { if ( (!szFilename) || (!strlen(szFilename)) ) return (FALSE); if ( (strchr(szFilename, '.')) || (strchr(szFilename, '\\')) || (strchr(szFilename, '/')) || (strchr(szFilename, ':')) || (strchr(szFilename, '<')) || (strchr(szFilename, '>')) || (strchr(szFilename, '*')) || (strchr(szFilename, '?')) || (strchr(szFilename, '|')) || (strchr(szFilename, '\"')) ) return (FALSE); return (TRUE); } I thought there might be a cleaner way to test a string before I used it for a file name.

      Programmer Glenn Earl Graham Austin, TX

      B Offline
      B Offline
      Brady Kelly
      wrote on last edited by
      #2

      Maybe slightly cleaner. The

      Path.GetInvalidFileNameChars

      should give you an array of invalid chars, which you can iterate and check

      IndexOf

      in your candidate file name.

      "Once in Africa I lost the corkscrew and we were forced to live off food and water for weeks." - Ernest Hemingway My New Blog

      E L 2 Replies Last reply
      0
      • E earlgraham

        In my old c++ days, I would use my old function below; BOOL IsValidFilename(const char *szFilename) { if ( (!szFilename) || (!strlen(szFilename)) ) return (FALSE); if ( (strchr(szFilename, '.')) || (strchr(szFilename, '\\')) || (strchr(szFilename, '/')) || (strchr(szFilename, ':')) || (strchr(szFilename, '<')) || (strchr(szFilename, '>')) || (strchr(szFilename, '*')) || (strchr(szFilename, '?')) || (strchr(szFilename, '|')) || (strchr(szFilename, '\"')) ) return (FALSE); return (TRUE); } I thought there might be a cleaner way to test a string before I used it for a file name.

        Programmer Glenn Earl Graham Austin, TX

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

        I'd just try it and catch the exception if any. Let the OS/framework determine validity; it knows best.

        P 1 Reply Last reply
        0
        • B Brady Kelly

          Maybe slightly cleaner. The

          Path.GetInvalidFileNameChars

          should give you an array of invalid chars, which you can iterate and check

          IndexOf

          in your candidate file name.

          "Once in Africa I lost the corkscrew and we were forced to live off food and water for weeks." - Ernest Hemingway My New Blog

          E Offline
          E Offline
          earlgraham
          wrote on last edited by
          #4

          Thanks here is the final code it works perfectly...

          bool IsValidFilename(String ^fileName)
          {
            if ( String::IsNullOrEmpty( fileName ) == true )
              return false;
            
            array^ invalidFileChar = System::IO::Path::GetInvalidFileNameChars();
          
            for each ( Char ^i in invalidFileChar )
            {
              if ( fileName->Contains(String::Format("{0}", i)) )
              {
                String ^tmp = String::Format(L" '{0}'  is invalid in a file name.\n", i);
                System::Windows::Forms::MessageBox::Show(gcnew String(tmp),gcnew String(L"Warning"), 
                  MessageBoxButtons::OK);
                return false;
              }
            }
          
            return true;
          }
          

          Programmer Glenn Earl Graham Austin, TX

          P 1 Reply Last reply
          0
          • P PIEBALDconsult

            I'd just try it and catch the exception if any. Let the OS/framework determine validity; it knows best.

            P Offline
            P Offline
            pbraun
            wrote on last edited by
            #5

            But if its speed you want, catching the exception may not be the best solution.

            Phil

            P 1 Reply Last reply
            0
            • E earlgraham

              Thanks here is the final code it works perfectly...

              bool IsValidFilename(String ^fileName)
              {
                if ( String::IsNullOrEmpty( fileName ) == true )
                  return false;
                
                array^ invalidFileChar = System::IO::Path::GetInvalidFileNameChars();
              
                for each ( Char ^i in invalidFileChar )
                {
                  if ( fileName->Contains(String::Format("{0}", i)) )
                  {
                    String ^tmp = String::Format(L" '{0}'  is invalid in a file name.\n", i);
                    System::Windows::Forms::MessageBox::Show(gcnew String(tmp),gcnew String(L"Warning"), 
                      MessageBoxButtons::OK);
                    return false;
                  }
                }
              
                return true;
              }
              

              Programmer Glenn Earl Graham Austin, TX

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

              That doesn't look like C# to me. :~

              1 Reply Last reply
              0
              • P pbraun

                But if its speed you want, catching the exception may not be the best solution.

                Phil

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

                Absolutely, why check what the OS/framework will check anyway? That's wasteful. The custom check may be faulty, causing a false valid or invalid. A false valid will likely result in an exception anyway, so you've wasted the time on the extra check, plus the time writing the faulty check. I know I couldn't write a filename validity checking routine as fast and accurate as the built-in one. You don't know to what OSs the framework may be ported in future (I know, it's unlikely) and what their validity rules are. I could certainly see adding some additional checking, like ensuring the name doesn't include a SPACE, or is 8.3 or something, but other than that you're just wasting your time. This is a wheel best not reinvented.

                1 Reply Last reply
                0
                • E earlgraham

                  In my old c++ days, I would use my old function below; BOOL IsValidFilename(const char *szFilename) { if ( (!szFilename) || (!strlen(szFilename)) ) return (FALSE); if ( (strchr(szFilename, '.')) || (strchr(szFilename, '\\')) || (strchr(szFilename, '/')) || (strchr(szFilename, ':')) || (strchr(szFilename, '<')) || (strchr(szFilename, '>')) || (strchr(szFilename, '*')) || (strchr(szFilename, '?')) || (strchr(szFilename, '|')) || (strchr(szFilename, '\"')) ) return (FALSE); return (TRUE); } I thought there might be a cleaner way to test a string before I used it for a file name.

                  Programmer Glenn Earl Graham Austin, TX

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

                  Or a Regular Expression, matching any of the invalid characters.

                  B 1 Reply Last reply
                  0
                  • B Brady Kelly

                    Maybe slightly cleaner. The

                    Path.GetInvalidFileNameChars

                    should give you an array of invalid chars, which you can iterate and check

                    IndexOf

                    in your candidate file name.

                    "Once in Africa I lost the corkscrew and we were forced to live off food and water for weeks." - Ernest Hemingway My New Blog

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

                    String.IndexOfAny() seems appropriate here. :)

                    Luc Pattyn [Forum Guidelines] [My Articles]


                    this weeks tips: - make Visual display line numbers: Tools/Options/TextEditor/... - show exceptions with ToString() to see all information - before you ask a question here, search CodeProject, then Google


                    1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      Or a Regular Expression, matching any of the invalid characters.

                      B Offline
                      B Offline
                      Brady Kelly
                      wrote on last edited by
                      #10

                      I like that idea. A regex over a path size string should be blindingly fast as well.

                      "Once in Africa I lost the corkscrew and we were forced to live off food and water for weeks." - Ernest Hemingway My New Blog

                      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