我试图通过ASP.NET从服务器获取文件列表。我有这个代码,它从我的计算机上的文件夹中获取文件列表,现在我要做的是从实际服务器获取文件,我已经搜索过这个,但发现一切都非常复杂。如果有人能帮助我或指出我想要做的方向,那就太好了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using FTPProject.Models;
namespace FTPProject.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
var uploadedFiles = new List<UploadedFile>();
var files = Directory.GetFiles(Server.MapPath("~/UploadedFiles"));
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
var uploadedFile = new UploadedFile() { Name = Path.GetFileName(file) };
uploadedFile.Size = fileInfo.Length;
uploadedFile.Path = ("~/UploadedFiles/") + Path.GetFileName(file);
uploadedFiles.Add(uploadedFile);
}
return View(uploadedFiles);
}
}
}
更新
我尝试了以下内容:
在我的Web.Config中:
补充说:
<appSettings>
<add key="myPath" value="D:\Folder\PDF" />
</appSettings>
并在控制器中更改了此内容:
var myPath = WebConfigurationManager.AppSettings["myPath"];
var files = Directory.GetFiles(Server.MapPath(myPath));
当我运行此代码时,我收到此错误:
发生了'System.Web.HttpException'类型的异常 System.Web.dll但未在用户代码中处理
附加信息:'D:\ Folder \ PDF'是物理路径,但是a 虚拟路径是预期的。
注意:我的应用程序与D:\不在同一台服务器上,但我需要从D:\
获取文件列表答案 0 :(得分:14)
Server.MapPath
采用虚拟路径,例如:~/Folder/file.ext
。因此,您无法将D:\Folder\PDF
之类的物理路径传递给它。
访问远程文件系统的语法不同,您需要UNC文件路径。在您的配置文件中,myPath应该与\\servername\d$\Folder\PDF
类似,您不需要对Server.MapPath
进行任何调用,并且您的站点进程正在运行的用户应该是您正在访问的服务器上的管理员。
或者您可以专门共享文件夹并为您的Web服务器运行的帐户授予权限,然后您不需要管理员权限(这更安全)。然后UNC路径就像\\servername\sharename
。
答案 1 :(得分:1)
Server.MapPath指定映射到物理目录的相对或虚拟路径。
Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
一个例子:
我们假设您将网站应用程序(http://www.example.com/)指向
C:\的Inetpub \ wwwroot的
并在
中安装了您的商店应用程序(子网站为IIS中的虚拟目录,标记为应用程序)d:\的WebApp \店
例如,如果您在以下请求中调用Server.MapPath:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
然后:
Server.MapPath(".")1 returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
如果Path以正向(/)或反斜杠()开头,则MapPath方法返回路径,就像Path是一个完整的虚拟路径一样。
如果Path不以斜杠开头,则MapPath方法返回相对于正在处理的请求的目录的路径。