2009-08-03 92 views
2

我试图加载我知道名称的一部分文件加载System.IO.FileStream(并知道它会是我所知道的部分被唯一标识。)使用通配符

这里它的精神:

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); 
    } 
} 

4号线是我需要帮助的地方。如果我说fileName +“*”,那么在“ID - Env - ”之后我会得到“ID - Env - *”而不是匹配任何文件的通配符(我有ID和Env的真正变量,它们在这里没有显示。)

有什么办法可以说“匹配任何符合开头的文件”吗?

(我正在使用VS 2008 SP1和.NET 3.5 SP1)

感谢您的任何帮助。

回答

4

的第一个结果使用名称你需要找到你想要的文件,你打开一个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 
{ 
//... 
} 
+0

我最喜欢你的例子,但System.IO.Directory.GetFiles不返回类型FileInfo []。它返回一个字符串列表。 – Vaccano 2009-08-03 21:22:36

+0

我用String []作为结果运行它,并且在System.IO.Directory.GetFiles上得到了一个ArgumentException。 (路径中的非法字符)。 – Vaccano 2009-08-03 21:24:02

1

您可以使用Directory.GetFiles()方法获取与模式相匹配的文件的集合,然后根据结果使用流。

+0

谁会投下来? – 2009-08-04 00:45:00

1

System.IO.Directory.GetFiles()

1

不,但它是微不足道的做你自己。

private string ResolveWildcardToFirstMatch(string path) 
{ 
    return Directory.GetFiles(Path.GetDirectoryName(path), 
           Path.GetFileName(path) + "*")[0]; 
} 
1

例中使用通配符:

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