views:

548

answers:

5

I am trying to load a file that I know part of the name (and know that it will be uniquely identified by the part that I know.)

Here is the jist of it:

string fileName = ID + " - " + Env + " - ";
byte[] buffer;
using (FileStream fileStream = new FileStream(Server.MapPath("~") + 
  fileName + "*", FileMode.Open))
{
    using (BinaryReader reader = new BinaryReader(fileStream))
    {
        buffer = reader.ReadBytes((int)reader.BaseStream.Length);
    }
}

Line 4 is where I need help. If I say fileName+"*" then I will get "ID - Env - *" instead of a wildcard matching any file after "ID - Env -" (I have real vars for ID and Env, they are just no shown here.)

Is there any way to say "match on any file that fits the beginning"?

(I am using VS 2008 SP1 and .NET 3.5 SP1)

Thanks for any help.

+1  A: 

You could use the Directory.GetFiles( ) method to get a collection of files that match the pattern first and then work with the stream based on the result.

Ed Swangren
Who would vote this down?
Ed Swangren
+1  A: 

Use the Name from the first result of System.IO.Directory.GetFiles()

Joel Coehoorn
+2  A: 

You'll need to locate the file you want before you open a FileStream.

string[] files = System.IO.Directory.GetFiles(Server.MapPath("~"), fileName + "*");

if(files.Length == 1) // We got one and only one file
{
   using(BinaryReader reader = new BinaryReader(new FileStream(files[0])))
   {
       // use the stream
   }
}
else // 0 or +1 files
{
 //...
}
Adam Robinson
I liked your example best, but System.IO.Directory.GetFiles does not return type FileInfo[]. It returns a string list.
Vaccano
I ran it with String[] as the result and I got an ArgumentException on the System.IO.Directory.GetFiles. (Illegal characters in path).
Vaccano
Only the 2-argument version accepts wildcards.
Richard Berg
DirectoryInfo.GetFiles returns a FileInfo[]
Ed Swangren
@Vaccano: Thanks, I've edited the post. I'm coding off the top of my head here ;)
Adam Robinson
+1  A: 

No, but it's trivial to do yourself.

private string ResolveWildcardToFirstMatch(string path)
{
    return Directory.GetFiles(Path.GetDirectoryName(path), 
                              Path.GetFileName(path) + "*")[0];
}
Richard Berg
This has the potential to blow up quite easily...
Adam Robinson
Yes, it does. Hopefully nobody is copy/pasting 5-second API samples into production code!
Richard Berg
+1  A: 

Example using wild cards:

  string[] fileNames = System.IO.Directory.GetFiles(@"c:\myfolder", "file*");
  if (fileNames.Length > 0)
  {
    // Read first file in array: fileNames[0]
  }
Bernhof