0

I have a folder ("EDI") [editions] with .txt files inside (01,02,03,04) I have this functional code:

ListBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath & "\Cat\EDI\", "01.txt"))
ListBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath & "\Cat\EDI\", "02.txt"))
ListBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath & "\Cat\EDI\", "03.txt"))

until 68. Each file contains a list songs. But if I try to reduce the code implementing at "For Loop", as:

For i = 1 To 70
           ListBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath & "\Cat\EDI\", (i) & ".txt"))
Next

I get an error at (i) & ".txt". Says: "String cannot be converted in coding" How can i solve?. Some to take in care is the name of the text files are 01.txt,02.txt WITH 2 NUMBERS, also the "for-loop" automatically changes 01 into 1

or better... How can i load all the text lines of all existent text files at folder?

I already have the list of files if it needed, I use this code to get all txt file names into another ListBox:

Dim newroot As String
newroot = (Application.StartupPath & "\Cat\EDI\")
listbox1.items.AddRange(IO.Directory.GetFiles(newroot, "*.txt").
               Select(Function(f) IO.Path.GetFileNameWithoutExtension(f)))
arc95
  • 97
  • 1
  • 8
  • Type this at the top of the code file "Option Strict On" (without the quotes). Then fix all the issues identified by VS. Also, investigate the `ToString` method on integers; specifically the one that takes a format string. "How can i solve?" - learn that the documentation is your friend (most of the time at least). – TnTinMn Feb 18 '18 at 03:22

2 Answers2

0

The following uses an Interpolated String denoted by the $ preceding the string. This will call .ToString for you on the integer in the { }

Private Sub FileNamesInLoop()
        For i As Integer = 1 To 9
            ListBox1.Items.Add($"0{i}.txt")
        Next
        For i2 As Integer = 10 To 68
            ListBox1.Items.Add($"{i2}.txt")
        Next
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27
0

You can use the Integer.ToString(format) overload and specify number format 00. Doing so will always add a leading zero for numbers < 10, i.e:

  • 5.ToString("00") becomes 05
  • 9.ToString("00") becomes 09
  • 23.ToString("00") becomes 23

Here's how you'd do it:

For i = 1 To 68
    ListBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath & "\Cat\EDI\", i.ToString("00") & ".txt"))
Next

Though I highly suggest you switch to Path.Combine() rather than concatenating the paths yourself, as it will ensure everything's done properly:

For i = 1 To 68
    ListBox2.Items.AddRange(File.ReadAllLines(Path.Combine(Application.StartupPath, "Cat", "EDI", i.ToString("00") & ".txt")))
Next
Visual Vincent
  • 18,045
  • 5
  • 28
  • 75