2009-08-03 121 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] 
    }