当前位置: 移动技术网 > IT编程>开发语言>c# > C#遍历文件夹后上传文件夹中所有文件错误案例分析

C#遍历文件夹后上传文件夹中所有文件错误案例分析

2019年07月18日  | 移动技术网IT编程  | 我要评论

asp.net是没有直接选取文件夹的控件的,我也不知道,如果大家有的话可以一起交流下。后来我想着应该有三种方法:

①先将文件夹压缩后上传服务器,然后再服务器上解压;

②获得文件夹名及目录,然后遍历文件夹下面的文件以及子文件夹,循环上传;

③是使用acitivex控件。
那我果断就先通过上传对话框获得文件夹名和文件夹所在的系统文件路径,可是接下来就错愕了,一开始是想使用javascript遍历文件夹的

1  var fso = new activexobject("scripting.filesystemobject");
2  var f = fso.getfolder(document.all.fixfolder.value);
3  var fc = new enumerator(f.files);

  但是发现遍历不了,才得知要想创建fso对象,操作文件,必须对该文件要有足够的权限才行,这样太麻烦了,于是我采取用c#来遍历文件夹,通过写一个ashx文件,在html里通过action将浏览的数据传送过来

以下是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控件才能实现。
从安全权限来分析,确实也是不允许的,否则我写一个网页,里面嵌入这段js代码,你一打开这个网页,js就可以开始慢慢的去遍历你的硬盘,把你的文件都上传到服务器。只有用户通过input控件自己选择的文件,才允许上传。
本文只是小编进行解决问题的一个思路并不是一个正确的方法,目的在于和大家进行学习交流,获得更好的解决办法。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网