在C#中创建Direcotry [英] Direcotry Creation in C#
问题描述
您好,
我正在尝试使用此代码段在c#中创建目录
Hello,
I'm trying to create directory in c# using this code snippet
public JsonResult Upload()
{
try
{
DirectoryInfo di =
Directory.CreateDirectory("~/Images_LL/Timeline/" + "userid" + Convert.ToInt32(Session["userid"]) + "");
}
catch (ArgumentNullException ex)
{
//throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
此行不会引发异常,但也不会创建目录。我正在以管理员身份运行visual studio。
请帮我弄清楚我已经在catch块中逐个尝试了所有异常。
抛出异常而不是生成目录。
this line throws no exception but directory is also not created. I'm running visual studio as administrator.
Please help me figure out I have tried all exceptions one by one in catch block.
Neither throws exception not makes directory.
推荐答案
你正在传递一个app相对路径。目录
类对ASP.NET路径一无所知。您需要首先将应用程序相对路径映射到物理路径:
You're passing in an app-relative path. TheDirectory
class doesn't know anything about ASP.NET paths. You need to map the app-relative path to a physical path first:
string virtualPath = string.Format("~/Images_LL/Timeline/userid{0}", Convert.ToInt32(Session["userid"]);
string physicalPath = Server.MapPath(virtualPath);
DirectoryInfo di = Directory.CreateDirectory(physicalPath);
另外,不要使用 throw ex;
来重新抛出异常。如果这样做,你将破坏堆栈跟踪。使用 throw;
代替。
并且不要捕获你不会处理的异常。立即捕获异常重新抛出它没有任何好处。只需删除整个 catch(Exception ex){...}
block。
Also, don't use throw ex;
to re-throw an exception. If you do, you'll destroy the stack-trace. Use throw;
instead.
And don't catch exceptions that you're not going to handle. Catching an exception and immediately re-throwing it has no benefit. Just remove the entire catch (Exception ex) { ... }
block.
使用MapPath得到物理l网站空间中路径的位置。
https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath(v = vs.110)的.aspx [ ^ ]
Use MapPath to get the physical location of the path in your webspace.
https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath(v=vs.110).aspx[^]
Directory.CreateDirectory(Server.MapPath("~/Images_LL/Timeline/") + "userid" ...
这篇关于在C#中创建Direcotry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!