使用C#.NET创建相关文件夹

4

大家好,我正在尝试使用C# MVC3创建文件夹。我在我的控制器中有以下代码:

string path = Path.Combine("~/Content/albums", album.title.Replace(" ", ""));
Directory.CreateDirectory(path);

但是它似乎没有创建文件夹。我已经尝试过使用不带相对路径的directory,它可以正常工作。

Directory.CreateDirectory("c:/test");

谢谢你


当您尝试此操作时,路径中包含什么? - Simon Edström
您需要为ASP.Net应用程序分配适当的权限,以便能够读写目录。其次,请查看HttpServerUtility.MapPath了解应用程序路径。http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx - Lloyd
hmm "~/Content/albums\gone" gone 是这张专辑的标题 @SimonEdström - Charbel Wakim
1
那听起来不像是一个有效的路径;-) - Simon Edström
2个回答

8

如果在控制器中,请首先尝试使用Server.MapPath;如果在控制器外部,则尝试使用System.Web.Hosting.HostingEnvironment.MapPath。它们都能够将虚拟资源路径映射到物理路径。因此:

string contentPath = Server.MapPath("~/Content/albums");
string path = Path.Combine(contentPath, album.title.Replace(" ", ""));

然后创建目录。


2

尝试使用这个替代方案,因为你指出的路径无效。

 string physicalPath = Server.MapPath("~/Content/albums");
 string path = Path.Combine(physicalPath , album.title.Replace(" ", ""));

 Directory.CreateDirectory(path);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接