C#遍历文件夹后上传文件夹中所有文件错误案例分析
asp.net是没有直接选取文件夹的控件的,我也不知道,如果大家有的话可以一起交流下。后来我想着应该有三种方法: ①先将文件夹压缩后上传服务器,然后再服务器上解压; ②获得文件夹名及目录,然后遍历文件夹下面的文件以及子文件夹,循环上传; ③是使用AcitiveX控件。 1 var fso = new ActiveXObject("Scripting.FileSystemObject"); 以下是C#遍历文件夹之后上传文件夹下的所有文件引用片段: <%@ WebHandler Language="C#" Class="folder" %> using System; using System.Web; using System.IO; public class folder : IHttpHandler { //采用递归的方式遍历,文件夹和子文件中的所有文件。 public void ProcessRequest(HttpContext context) { HttpRequest Request = context.Request; HttpResponse Response = context.Response; HttpServerUtility Server = context.Server; //指定输出头和编码 Response.ContentType = "text/html"; Response.Charset = "utf-8"; HttpFileCollection fs = HttpContext.Current.Request.Files; string newFilePath = Request.Form["sPath"]; if(fs.Count>0) { //fs[0]对应FindFile的dirPath就是指定目录,newFilePath绝对赢svrPath就是目标目录,也就是服务器上的目录 FindFile(fs[0].ToString(),newFilePath); } Response.Write("<script>parent.FileUploadDeal()</script>"); } //采用递归的方式遍历,文件夹和子文件中的所有文件。 public void FindFile(string dirPath,string svrPath) //参数dirPath为指定的目录,svrPath是目标目录 { //目标目录,也就是服务器上的目录 string sFilePath = System.Web.HttpContext.Current.Server.MapPath(svrPath); //string sFilePath = System.Web.HttpContext.Current.Server.MapPath(Request.Form["svrPath"]); //创建文件夹 if (!Directory.Exists(sFilePath)) Directory.CreateDirectory(sFilePath); //在指定目录及子目录下查找文件 DirectoryInfo Dir=new DirectoryInfo(dirPath); try { foreach(DirectoryInfo d in Dir.GetDirectories())//查找子目录 { FindFile(Dir+d.ToString()+"",svrPath+d.ToString()+""); //FindFile(Dir+d.ToString()+"",svrPath+d.ToString()+""); } foreach(FileInfo f in Dir.GetFiles()) //查找文件 { //f.SaveAs(Server.MapPath(svrPath + f.ToString()));//如果要保存到其他地方,注意修改这里 f.CopyTo(System.Web.HttpContext.Current.Server.MapPath(svrPath + f.ToString()),true); HttpContext.Current.Response.Write("4554132"); } } catch(Exception e) { ; } } public bool IsReusable { get { return false; } } } 原本以为这样就可以达到效果,但是却发现了一个致命的问题!因为Fileupload控件本身是不支持文件夹的上传,即使通过ashx也无法赋值给它。通过了解更多资料,得知,由于安全性原因,不可能直接在浏览器上通过代码直接上传本地文件夹,必须通过ActiveX控件才能实现。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |