Read a file, knowing only a part of its name

  • Thread starter Thread starter Jason
  • Start date Start date
J

Jason

I need to open a file for reading, but I only know part of it's name.

The file I want to read is in the format of xxx-yyyy-zzz.EXT

The last three digits of the file name are different on each pc, for example

PC7 has xxx-yyyy-zz1.ext
PC5 has xxx-yyyy-zz2.ext
PC3 has xxx-yyyy-zz8.ext

and so on.

I need to find out if that file exists by using the first 7 seven digits
and if it does exist, then open it up for reading.


The way I do this now is to loop through the folder, and look at the first
7seven digits using the substing method and if that name equals a constant
(xxx-yyyy) then I open that file.
It works, but it seems like extra work, plus depending on the number of
files it can eat up alot of time.


Any ideas
 
Jason,

Retrieve just the file names that begin with the known string:

Dim dirs As String() = Directory.GetFiles("c:\test", "123-4567*")

Then see how many files you got and proceed accordingly:

If dirs.Length = 1 Then
'Display the file name
MsgBox(dirs(0))
ElseIf dirs.Length = 0 Then
MsgBox("Not found")
Else
MsgBox("More than 1 file found")
End If

Kerry Moorman
 
I need to open a file for reading, but I only know part of it's name.

The file I want to read is in the format of xxx-yyyy-zzz.EXT

The last three digits of the file name are different on each pc, for
example

PC7 has xxx-yyyy-zz1.ext
PC5 has xxx-yyyy-zz2.ext
PC3 has xxx-yyyy-zz8.ext

Use FindFirstFile with "xxx-yyyy-???.ext" or use DirectoryInfo

(FindFirstFile exported from Kernel32.dll)

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=144544&SiteID=1
 
Kerry

That works great, but is there a way I can determine if that file first
exists?
CAn I do a ....

If ((Dim dirs As String() = Directory.GetFiles("c:\test", "123-4567*")) <>
true) Then
'File does not exist

or is there a easier way?

Thanks
 
Hi Jason,

Directory.GetFiles() returns a String array, not a boolean value, so you
can't do it that way.

In my opinion, this method will only return the names of matching files in
the folder, so they *have* to be existing, don't they ? Why would you need
to check if the file exists in this case ?

If you want to check if anything was returned at all, then just use Kerry's
method and check for the Length property of the returned String array.

Dim Dirs As String() = Directory.GetFiles("c:\test", "123-4567*")
If Dirs.Length > 0 then
'Atleast 1 file was found
Else
'No file matching this pattern was found
End if
 
Back
Top