C# 在 ASP.NET 中创建文件夹并将图像上传到该文件夹的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/740342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to create a folder and upload a image to that folder in ASP.NET?
提问by Etienne
Any code examples on how i must go about creating a folder say "pics" in my root and then upload a images from the file upload control in into that "pics" folder? If you don't want to give me all the code, i will be happy with a nice link also to show me how this will be done in VB.NET (C# is also ok).
关于我必须如何创建文件夹的任何代码示例在我的根目录中说“图片”,然后将文件上传控件中的图像上传到该“图片”文件夹中?如果你不想给我所有的代码,我会很高兴有一个很好的链接,向我展示这将如何在 VB.NET 中完成(C# 也可以)。
采纳答案by roman m
Try/Catch is on you :)
尝试/捕捉在你身上:)
public void EnsureDirectoriesExist()
{
// if the \pix directory doesn't exist - create it.
if (!System.IO.Directory.Exists(Server.MapPath(@"~/pix/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(@"~/pix/"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
{
// create posted file
// make sure we have a place for the file in the directory structure
EnsureDirectoriesExist();
String filePath = Server.MapPath(@"~/pix/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
}
else
{
lblMessage.Text = "Not a jpg file";
}
}
回答by Mike Geise
here is how I would do this.
这是我将如何做到这一点。
protected void OnUpload_Click(object sender, EventArgs e)
{
var path = Server.MapPath("~/pics");
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
var file = Path.Combine(path, upload.FileName);
upload.SaveAs(file);
}
回答by Naushad Ali
Create Folder inside the Folder and upload Files
在文件夹内创建文件夹并上传文件
DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/FolderName/") + txtNewmrNo.Text)); //Creating SubFolder inside the Folder with Name(which is provide by User).
string directoryPath = info+"/".ToString();
if (!info.Exists) //Checking If Not Exist.
{
info.Create();
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++) //Checking how many files in File Upload control.
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(directoryPath + Path.GetFileName(hpf.FileName)); //Uploading Multiple Files into newly created Folder (One by One).
}
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This Folder already Created.');", true);
}