Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Oct 1, 1996



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Changing File Extension

not having programmed in any of the BASIC languages, I am wondering if Visual Basic's string variable is in anyway similar to what a string variable is in C (i.e. is it defined as an array of characters in visual basic?) The reason I am asking this is that - I'd like to take the content of a text box (a file name) and then change the extension on the same file name to something else and put it in another text box - and I am not quite sure how to go about this in visual basic (the help file on the string variable was a bit brief...)

VB has a special datatype for String. You don't have to define it as an array of characters...just do "Dim temp as String" and it's a String.

The following code assumes:

  • You know that the "divider" character in your filename is a period
  • You don't know how many characters are in the extension (it will correctly parse file.c, file.au, file.txt, file.html, etc.)

    To test this code, make a form with two textboxes (leave the default names of Text1 and Text2). Paste the following code into the double-click event of Text2. Run the project and try it with various things (or nothing!) in Text1.

    I've commented the code heavily, hope everything's clear.

    Dim flag As Integer  'flag is used for the condition in the Do/Loop
    Dim x As Integer
    Dim temp As String
    'x is being used as a "counter" variable
    'we set its length here
    x = Len(Text1)
    'next line errortraps to make sure that it's not an
    'empty textbox
    If x > 0 Then
    Do While Not flag 'as long as flag is False...
    'next line picks out one character from the string.
    'the first pass through the loop will get the last
    'character in the string, the next pass will get
    'the next-to-the-last, etc. because we decrement
    'x by one in the next "If/End If" statement
    temp = Mid$(Text1, x, 1)
    If temp = "." Then
      flag = True
      x = x - 1
      x = x - 1
    End If
    'the next line gracefully exits the loop if
    'there's no period in Text1 at all
    If x = 0 Then flag = True
    'the next line first tests to make sure that
    'there was a period found in Text1... if so
    'it adds everything to the left of the period
    'and ".ext" and puts the resultant string into
    'Text2. You can remove the "If x > 0 Then" if
    'you think there might be an "extensionless"
    'filename in Text1.
    If x > 0 Then Text2 = Left$(Text1, x) & ".ext"
    End If
  • DevX Pro
    Comment and Contribute






    (Maximum characters: 1200). You have 1200 characters left.



    Thanks for your registration, follow us on our social networks to keep up-to-date