Visual Basic Developer Center >
Visual Basic Forums
>
Visual Basic Language
>
Read files in a directory
Read files in a directory
- Does anyone have a code sample of how to read files in a directory..what im looking to do is read a file name and run checks to verify its authenticity..then excute it...also looking for a code that would read the file name..for example files are called
WW487487.exe
WW154874.exe
WW244874.exe
I need code that will only read the numbers not the "WW" or the ".exe"
Thanks in advance!
Answers
- More suggestions - this code will do some filtering on the file name while looking for files, and will extract and try to convert to integer the number portion:
Module
Module1
Sub Main()
For Each file As String In System.IO.Directory.GetFiles("c:\", "ww??????.exe")
Dim value As Integer
'Cleanup full path to get the file name only
file = IO.Path.GetFileName(file)
If Integer.TryParse(file.Substring(2, 6), value) Then
Console.WriteLine(value)
End If
Next
End Sub
End Module
All Replies
- Well if you want to read all file in adirectory, this might be the way for you:
For Each srtFileName As String In System.IO.Directory.GetFiles(strYourDirectory)
System.Diagnostics.Process.Start(srtFileName)
Next
For that problem with the numbers, maybe there is a better solution, but I would make it like this:
Private Sub yourSub
Dim strFilenameWithNumbers As String
Dim count As Integer
For i = 1 to strFileName.Lenght
If IsNumeric(strFileName.Chars(i)) Then
strFilenameWithNumbers = strFilenameWithNumbers + strFileName.Chars(i)
End if
Next
End Sub
So I hope this works for you.
- An alternative to Thomas's second code snippet might be:
Private Function GetDigits(ByVal filename As String) As String
Dim strTemp As String
If filename.StartsWith("WW") Then ' This value could be passed in as a 2nd parameter if not fixed
' Remove first 2 and last 4 chars
strTemp = filename.Substring(2, (filename.Length - 6))
Else
' Not a file in this series, so ignore it
strTemp = ""
End If
Return strTemp
End Function
- More suggestions - this code will do some filtering on the file name while looking for files, and will extract and try to convert to integer the number portion:
Module
Module1
Sub Main()
For Each file As String In System.IO.Directory.GetFiles("c:\", "ww??????.exe")
Dim value As Integer
'Cleanup full path to get the file name only
file = IO.Path.GetFileName(file)
If Integer.TryParse(file.Substring(2, 6), value) Then
Console.WriteLine(value)
End If
Next
End Sub
End Module
- Thanks guys I will try these snippets out and see what works best. I appricate the help!
- Guys, do you know why I get an error message of file not found when I try running each of these codes?
Do you think maybe it is the version of VB (6.3)?

