【问题标题】:Load a System.IO.FileStream using a WildCard使用通配符加载 System.IO.FileStream
【发布时间】:2009-08-03 20:58:04
【问题描述】:

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

这是它的要点:

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)

感谢您的帮助。

【问题讨论】:

    标签: c# .net-3.5 file-io


    【解决方案1】:

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

    【讨论】:

    • 我最喜欢您的示例,但 System.IO.Directory.GetFiles 不返回类型 FileInfo[]。它返回一个字符串列表。
    • 我使用 String[] 运行它,结果在 System.IO.Directory.GetFiles 上出现 ArgumentException。 (路径中有非法字符)。
    • DirectoryInfo.GetFiles 返回一个 FileInfo[]
    • @Vaccano:谢谢,我已经编辑了帖子。我在这里写代码;)
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      使用System.IO.Directory.GetFiles()的第一个结果中的名称

      【讨论】:

        【解决方案4】:

        不,但自己做很简单。

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

        【讨论】:

        • 是的,确实如此。希望没有人将 5 秒的 API 示例复制/粘贴到生产代码中!
        【解决方案5】:

        使用通配符的示例:

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

        【讨论】:

          猜你喜欢
          • 2013-01-18
          • 2020-01-31
          • 2014-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-25
          • 1970-01-01
          相关资源
          最近更新 更多