converting spaces to "_" , but only for the filename

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maylortaylor
    New Member
    • Nov 2012
    • 72

    #1

    converting spaces to "_" , but only for the filename

    I'm trying to have it so that my textbox (which gets its input from a SaveFileDialog) will replace any spaces with an underscore.

    So far, this is the code i have.

    Code:
    Private Sub boxDestin_TextChanged(sender As Object, e As EventArgs) Handles boxDestin.TextChanged
    
            Dim removespaces As String
            removespaces = boxDestin.Text
    
            boxDestin.Text = Replace(removespaces, " ", "_")
    end sub
    But this changes every space in the file location to an underscore. The problem being that not all my directories have underscores...

    So for example, "C:\Users\J oe Smith\file name.txt"
    will become "C:\Users\Joe_S mith\file_name. txt"

    but you can obviously see the issues coming from that.

    Any suggestions?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You can use the LastIndexOf method to find the last occurrence of the "\" character. Substring out to the right of that character and do your replace and then concatenate it with the substring to the left of that character.

    Comment

    • PsychoCoder
      Recognized Expert Contributor
      • Jul 2010
      • 465

      #3
      To avoid a lot of string manipulation (I do whenever possible) you can use GetFileName() and GetDirectoryNam e(), something like this:

      Code:
      Dim file As String = saveFileDialog1.FileName
      Dim replaced As String = Path.GetFileName(file).Replace(" ", "_")
      
      TextBox1.Text = Path.GetDirectoryName(file) & "\" & replaced

      Comment

      • maylortaylor
        New Member
        • Nov 2012
        • 72

        #4
        Thank you psychoCoder. Your code worked perfectly well.

        Comment

        Working...