Reputation: 97
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)))
Upvotes: 0
Views: 65
Reputation: 18320
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
Upvotes: 0
Reputation: 15091
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
Upvotes: 0