Results 1 to 31 of 31

Thread: [RESOLVED] Adding to filename

  1. #1

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Resolved [RESOLVED] Adding to filename

    I have some code
    VB Code:
    1. ListBox1.Items.AddRange(System.IO.Directory.GetFiles(TextBox1.Text, "*.lib"))
    that makes a listbox filled with the path and filename of all the .lib files in a folder.
    I also have this code:
    VB Code:
    1. For Each itm As String In ListBox1.Items
    2.            <insert code here>
    3.         Next
    that will run through the lsitbox and do something with each item.

    On to the question.

    I was wondering how I, inside the second code, add something to the pathname.
    i.e. Change "c:\libraries\1234.lib" to "c:\libraries\ab_1234.lib"
    I know I could use
    VB Code:
    1. Name "c:\libraries\1234.lib" as "c:\libraries\ab_1234.lib"
    but I have to do that with a bunch of different files.

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Adding to filename

    You simply loop through each element in the array and perform a string manipulation procedure which I'm assuming you already know how to do. And once the array has been processed, THEN addrange() it.

  3. #3

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Could you elaborate on the string manipulation procedure? You assumed a bit too much

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Adding to filename

    VB Code:
    1. For Each Item As String In ListBox1.Items
    2.             Dim TargetIndex As Integer = Item.Length - Item.LastIndexOf("\")
    3.             Dim NewName As String = Item.Substring(0, TargetIndex) + "ab_" + Item.Substring(TargetIndex)
    4.             Rename(Item, NewName)
    5.         Next
    Last edited by ComputerJy; Jul 5th, 2006 at 12:52 PM.
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  5. #5

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Thanks.

    Could you explain your code a bit? I understand the last three lines but I'm having trouble understanding what comes before them.

  6. #6
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Adding to filename

    Sorry
    Fixed it
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  7. #7

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Ok, I understand it a bit more but the lines dimensioning new variables are confusing me.
    What are the output variables? i.e. What is the renamed file's variable? Is it "Item" or "NewName"?

  8. #8
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Adding to filename

    VB Code:
    1. Private Sub RenameFiles()
    2.         'Loop through all items in the listbox
    3.         For Each Item As String In ListBox1.Items
    4.             'Where does the file name start
    5.             Dim TargetIndex As Integer = Item.Length - Item.LastIndexOf("\")
    6.             'Add "ab_" to the file name as a prefix
    7.             Dim NewName As String = Item.Substring(0, TargetIndex) + "ab_" + Item.Substring(TargetIndex)
    8.             'Rename the file (the Rename sub is located in Microsoft.VisualBasic)
    9.             Rename(Item, NewName)
    10.         Next
    11.     End Sub
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  9. #9

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Is there any way to not write over the file, but just save the new name temporarily as a string?

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Adding to filename

    You've got it in NewName, if you don't rename the item, then the original is untouched. Of course, you might want to have both the old and new, and there are various ways to do this. Because NewName is declared within the For....Next loop, it doesn't have scope outside of that loop (no code can see it outside of that loop). Because of this, you might want to Dim the variables at a higher level of scope, such as in the sub, or even within the form class, or higher (though that's not advisable). It all depends on what other code has to be able to see that variable.

    The other issue is how long you want that other name to persist. As it stands, each time through the loop it will be overwritten by the next name. If you need to keep it longer than that, you will need an array of the modified names....but now I'm off on a tangent.
    My usual boring signature: Nothing

  11. #11

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    What I'm trying to do is populate three textboxes with different but similar info 1000's of times over. I need to keep the original file but copy the filename and put that in textbox1. Then I need to modify the pathname and put that in textbox2. Finally, I need to modify the extension and put it into textbox3.

    Imaging having to do this a thousand times over in commandline and now you can see why I'm making this proggy

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Adding to filename

    Yah, that's easy to see.

    However, in your example, you alter the filename, not the pathname.

    And while we're on the subject, let me mention that there are some excellent tools for working with file names and path names that might be of more use than playing with the strings as you are doing:

    Darn, just realized that I stripped all of that code out, so I don't have a good example for you.

    Ok, look up the Path class. In particular, look at Path.GetDirectory, Path.GetFileName, Path.HasExtension, and Path.GetExtension.

    In each case, you pass in the path that you have in the listbox, and you can use the first one to fill the first textbox, the second one to fill the second text box, and the fourth one to fill the third text box. Then you don't have to deal with all the substring stuff. Also, there are several other members of Path that might be of some passing interest to you.
    My usual boring signature: Nothing

  13. #13

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Ok, I'll look it up on F1 help and see what I come up with.

    Thanks!

  14. #14

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Ok, well. It looks like MSDN is going to be fo little use. I get what the path.whatever is used for, but I also need to know how to change the filename/extension.

    Ex: -note: Changes from first path are marked in bold

    What is in the listbox: u:\files\work\library.lib
    What I need for textbox1: u:\files\work\library.lib
    What I need for textbox2: u:\converted_files\job\ab_library.lib
    What I need for textbox3: u:\converted_files\job\ab_library.log

  15. #15
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Adding to filename

    Oh, that's a bit different.

    Assume that what is in the listbox is moved into a variable called st1.

    Path.GetFileName(st1) will return Library.lib.
    It looks like textbox1 can be st1
    It looks like textbox2 could be simply "u:\converted_files\job\ab_" & st1
    For textbox3, you could use "u:\converted_files\job\ab_" & st2

    where st2 = st1.substring(0,st1.length - st1.IndexOf(".")) & ".log"

    I may be off on the second argument of substring, I may have the subtraction off by one. I'd want to test it before I used it.
    My usual boring signature: Nothing

  16. #16
    PowerPoster
    Join Date
    Aug 2005
    Location
    College Station, TX
    Posts
    4,521

    Re: Adding to filename

    You can also use simple Strings.Replace if you dont mind using Runtime Functions. Or you can also look into Regex.Replace if Runtime Functions seem to perturb you, although .Substring (that shaggy posted) will probably yield the best performance. Below is an example of using Strings.Replace...
    VB Code:
    1. Dim MyString As String = "u:\files\work\library.lib"
    2.         Dim Second As String = Strings.Replace(MyString, "files\work\", "converted_files\job\ab_")
    3.         Dim Third As String = Strings.Replace(Second, ".lib", ".log")
    4.         MessageBox.Show(Second)
    5.         MessageBox.Show(Third)

  17. #17

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Wow, thank you both! I'll try them as soon as I get VB installed on my home comp.
    You guys posted these literally right after I got off of work

    PS-Raised both your reps

  18. #18

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Shaggy, how do I declare path? O rather, what do I declare it as?

    (I'm so sad )

  19. #19
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding to filename

    You don't declare Path as anything. It is a class in the System.IO namespace. You can either refer to it as System.IO.Path or just IO.Path, or else import the System.IO namespace and refer to it as Path. You import a namespace either project-wide in the project properties or else file-specific at the top of the code file.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  20. #20

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    How do I do that?

    Like I said...I'm sad

  21. #21
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  22. #22

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Ok, the error is gone. I'll test it tomorrow at work.
    Thanks again

  23. #23

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Uh, oh.

    On first test, I got really weird errors. I looked through the code and found that Path.GetFileName(st1) returns the entire path and filename. Thus breaking the program. Does anyone know what I should use to get the filename alone?

  24. #24

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Never mind. I got that figured out.

    Now, I'm having a problem with this:
    VB Code:
    1. Dim st3 As String = st1.Substring(0, st2.Length - st2.IndexOf(".")) & ".log"
    Note- I changed up the variables a bit, but still works trust me

    Anyways, instead of "u:\converted_files\job\ab_library.log" I get "u:\s.log"

    Double-you tee eff mate

  25. #25
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding to filename

    Um, Path.GetFileName does not retrun the entire path and filename. I don't know what you're doing but it ain't right.
    Attached Images Attached Images  
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  26. #26

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    If you noticed, I replied to myself saying I got it figured out.

    What I need help on is the last textbox. (see post #14 and my problem in post #24)

  27. #27
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Adding to filename

    Assuming str1 is the original string,

    VB Code:
    1. Dim str2 As String = str1.Replace(str1.Substring(str1.IndexOf("\") + 1, str1.Length - str1.LastIndexOf("\") - 1), "converted_files\job\ab_")
    2.         MessageBox.Show(str2)
    3.         Dim str3 As String = str2.Substring(0, str2.LastIndexOf(".")) + ".log"
    4.         MessageBox.Show(str3)

  28. #28
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding to filename

    Well given that you're still using Substring you obviously still haven't figured out how to use the Path class properly.
    VB Code:
    1. Const FOLDER_PATH As String = "converted_files\job"
    2. Const FILE_PREFIX As String = "ab_"
    3.  
    4. Dim path1 As String = "u:\files\work\library.lib"
    5. Dim path2 As String = IO.Path.Combine(IO.Path.Combine(IO.Path.GetPathRoot(path1), _
    6.                                                       FOLDER_PATH), _
    7.                                       FILE_PREFIX & IO.Path.GetFileName(path1))
    8. Dim path3 As String = IO.Path.ChangeExtension(path2, ".log")
    9.  
    10. MessageBox.Show(String.Join(Environment.NewLine, _
    11.                             New String() {path1, _
    12.                                           path2, _
    13.                                           path3}))
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  29. #29
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Adding to filename

    Never seen that before, pretty obvious why.

    ChangeExtension does pretty much the same thing doesn't it?

  30. #30
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Adding to filename

    The thing I like most about the members of the Path class are that they are self-documenting. IO.Path.ChangeExtension makes it pretty obvious what's happening, whereas the use of string manipulation is much more generic and it's not obvious at a glance what is happening unless appropriate commenting is used. The only issue I have is that multiple uses of Combine gets a bit long-winded. I'd not use it more than twice in one line of code. Here's the actual implementation of ChangeExtension:
    Code:
    public static string ChangeExtension(string path, string extension)
    {
          if (path == null)
          {
                return null;
          }
          Path.CheckInvalidPathChars(path);
          string text1 = path;
          int num1 = path.Length;
          while (--num1 >= 0)
          {
                char ch1 = path[num1];
                if (ch1 == '.')
                {
                      text1 = path.Substring(0, num1);
                      break;
                }
                if (((ch1 == Path.DirectorySeparatorChar) || (ch1 == Path.AltDirectorySeparatorChar)) || (ch1 == Path.VolumeSeparatorChar))
                {
                      break;
                }
          }
          if ((extension == null) || (path.Length == 0))
          {
                return text1;
          }
          if ((extension.Length == 0) || (extension[0] != '.'))
          {
                text1 = text1 + ".";
          }
          return (text1 + extension);
    }
    Last edited by jmcilhinney; Jul 8th, 2006 at 10:52 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  31. #31

    Thread Starter
    Addicted Member bobabot1's Avatar
    Join Date
    Jul 2006
    Location
    The Restaurant at the End of the Universe
    Posts
    162

    Re: Adding to filename

    Thank you all! I finally got it working.

    Thanks again!

Posting Permissions

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



Click Here to Expand Forum to Full Width