显示 ASP.NET MVC 4 项目目录中的文件类型

Display filetype from directory in ASP.NET MVC 4 Project

我目前正在学习 ASP.NET MVC 4。

我想显示位于网页目录中的 .cs.cpp 文件。但是不知何故我得到了多文件类型显示的异常。

下面的代码行给出了异常:

string pattern ="*.cs|*.cpp";

到目前为止我写了下面的代码:

public ActionResult Contact()
{
    string pattern = "*.cs";
    //string pattern ="*.cs|*.cpp";  // this line does not work  
    ViewBag.Message = "Your contact page.";
    DirectoryInfo dirInfo = new DirectoryInfo(@"f:\");
    List<string> filenames = dirInfo.GetFiles(pattern).Select(i => i.Name).ToList();
    ViewBag.data = filenames;
    return View(filenames);
}

查看代码如下所示:

@{
    ViewBag.Title = "Contact";
}
<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
</hgroup>
<table bgcolor="#00FF00">
    @foreach (var item in (List<string>)ViewBag.data)
    {
        <tr>
            <th>@item   <br></th>

        </tr>
    }
</table>

DirectoryInfo.GetFiles(pattern) 只允许一个模式。它不像你在创建普通对话框时设置的过滤器。

如果你想要多个模式,你可以创建自己的扩展方法,这里有一些例子:: GetFiles with multiple extensions

您将需要执行以下操作:

        string pattern = "*.cs";
        ViewBag.Message = "Your contact page.";
        DirectoryInfo dirInfo = new DirectoryInfo(@"f:\");
        List<string> filenames = new List<string>();
        foreach (FileInfo f in dirInfo.GetFiles(pattern))
        {
            filenames.Add(f.Name);  //or f.FullName to include path
        }
        pattern = "*.cpp";
        foreach (string f in dirInfo.GetFiles(pattern))
        {
            filenames.Add(f);
        }

        ViewBag.data = filenames;
        return View(filenames);

或者,像这样:

        public ActionResult Contact()
    {

        string pattern = "*.cs|*.cpp";
        ViewBag.Message = "Your contact page.";
        DirectoryInfo dirInfo = new DirectoryInfo(@"f:\");
        List<string> filenames = new List<string>();
        string[] temp = pattern.Split('|');
        for (int i = 0; i < temp.Length; i++)
        {
            filenames.AddRange(GetFiles(temp[i]));
        }
        ViewBag.data = filenames;
        return View(filenames);
    }

    public List<string> GetFiles(string pattern) {
        DirectoryInfo dirInfo = new DirectoryInfo(@"f:\");
        List<string> filenames = new List<string>();
        foreach (FileInfo f in dirInfo.GetFiles(pattern))
        {
            filenames.Add(f.Name);  //or f.FullName to include path
        }
        return filenames;
    }

这样做的好处是,您将有机会在将列表返回到您的视图之前对其进行排序和进一步过滤。