我目前正在学习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);
}
View代码如下:
@{
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>
答案 0 :(得分:0)
DirectoryInfo.GetFiles(pattern)
仅允许单一模式。它与创建公共对话框时设置的过滤器不同。
如果你想要多个模式,你可以创建自己的扩展方法,这里有一些例子:: GetFiles with multiple extensions
答案 1 :(得分:0)
你需要做这样的事情:
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;
}
关于这一点的好处是,您有机会进行排序,并在将列表返回到您的视图之前进一步过滤列表。