c# - 使用 WildCard 加载 System.IO.FileStream

标签 c# .net-3.5 file-io

我正在尝试加载一个我知道部分名称的文件(并且知道它将由我知道的部分唯一标识。)

这里是它的主旨:

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)

感谢您的帮助。

最佳答案

在打开 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
{
 //...
}

关于c# - 使用 WildCard 加载 System.IO.FileStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1224594/

相关文章:

c# - 列表扩展方法的 Microsoft.Maintainability 错误

linux - 在 linux 中删除打开的文件时内部会发生什么

c# - 在包含固定数组的托管不安全结构上,C# 'fixed' 语句的开销是多少?

c# - 在主机 ('Anonymous' 上配置的身份验证方案不允许在绑定(bind) 'WebHttpBinding' 上配置的那些 ('Basic' )

c# - 在C#类库中传递上下文,在不使用static的情况下寻找 "easy"的方式

.NET 构建过程

.net - 将返回 List<employee> 的方法绑定(bind)到 gridview

c# - 我应该为此创建一个单独的类吗?

c# - 如何将图像文件读取到 byte[]?

c# - 如何获取所有任务