如果添加使用System.IO或引用它,這應該找到在App_Data文件夾中所有.xml文件,在你的應用環境:
DirectoryInfo di = new DirectoryInfo(Server.MapPath("/App_Data"));
var fi = di.EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly);
// fi should contain the enumeration of files found at that path
// you can iterate over fi and have all the file info of each file found
[更新]
如果您已經解析了路徑字符串,則可以將整個Server.MapPath(「/ App_Data」)替換爲桌面應用程序的路徑,其餘部分保持不變。
要遍歷集合只需使用一個foreach循環,如:
foreach (FileInfo file in fi)
{
string s = "File Name: " + file.Name + "\r";
s += "Full Path: " + file.FullName + "\r";
s += "File Ext.: " + file.Extension + "\r";
MessageBox.Show(s);
}
[更新2]
由於OP指的是一個網絡方案
通過增加使用制度.Web.Hosting聲明到我的控制器我能夠在mvc示例應用程序中測試'HostingEnvironment.MapPath'。 這是我想出來的。
本例找到虛擬路徑'/ App_Data',收集它在路徑中找到的'.xml'文件。然後它迭代集合並將每個文件的內容讀入數組元素。 最後,它將文件名顯示爲視圖中的鏈接,以及每個文件的內容帶有標題#。請記住,這可能不是最優化的代碼示例。
C#代碼:MVC中的控制器
DirectoryInfo di = new DirectoryInfo(HostingEnvironment.MapPath("/App_Data"));
var fi = di.EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly);
ViewBag.Files = fi;
string[] fs = new string[fi.Count()];
int fc = fi.Count();
int x = 0;
foreach (FileInfo f in fi)
{
StreamReader sr = new StreamReader(f.FullName);
fs[x] = sr.ReadToEnd();
sr.Close();
if (x < fc) x++;
}
ViewBag.Contents = fs;
ViewBag.ContCount = fc;
HTML:在查看
<div>
<h3>Files Found:</h3>
<p>
@foreach (FileInfo f in @ViewBag.Files)
{
<a href="@f.FullName">@f.Name</a><br />
}
</p>
</div>
<div>
<h3>File Contents:</h3>
@for (int c = 0; c < @ViewBag.ContCount; c++)
{
<h4>Heading @(c)</h4>
<p>
@ViewBag.Contents[@c]
</p>
<hr />
}
</div>
只是因爲它存在於你的源代碼樹並不意味着它存在於您的可執行文件編譯爲的應用程序二進制文件夾中。 –
「AppDomain.CurrentDomain.BaseDirectory」的值是否與您認爲的完全相同? – grek40
我認爲,而不是'AppDomain.CurrentDomain.BaseDirectory + 「\\ App_Data \\'''你想''Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)' –