本文实例讲述了asp.net获取服务器指定文件夹目录文件并提供下载的方法。分享给大家供大家参考。具体实现方法如下:
' x& C7 ?4 A; e" f, ?6 t) c6 b复制代码 代码如下:string dirpath = httpcontext.current.server.mappath(uploads/);5 f% v/ e, q! n* `# K$ i: X
if (directory.exists(dirpath))) U4 [! C, [: t/ T& X, f# x2 o
{ g) w0 o7 l7 i4 D; y3 r# }
//获得目录信息# p3 `+ D, i' _' \
directoryinfo dir = new directoryinfo(dirpath);
$ `, H) b% r" v//获得目录文件列表
7 L* j( Z: t3 a3 {4 B2 P$ k* Bfileinfo[] files = dir.getfiles(*.*);3 h0 `; y+ T' K, d
string[] filenames = new string[files.length];/ \1 \4 J8 w5 f& R5 q
//临时数据表
8 C I: A7 y# ^; u' edatatable dt = new datatable();& z' D( j. m4 l4 G
dt.columns.add(filename);
4 T* s8 l+ Z2 u# ~' B. P: ]/ U0 E1 S' k8 I9 q1 U$ u+ _' v
foreach (fileinfo fileinfo in files)
0 U' A. ]$ V, U. E4 ^{. B1 ]. Y% o6 @7 s
datarow dr = dt.newrow();) c- n3 X# H( p) x. `& L
dr[filename] = fileinfo.name;
" N) v2 @* A' z- K4 b# m& _% s( Edt.rows.add(dr);
+ b' ~4 U. Z+ J ~) H}
5 w2 ~8 M2 y# }2 J4 p, M6 Xrepeater1.datasource = dt;
7 ^; _$ Y' T% N8 I8 `/ F1 y: `9 Drepeater1.databind();
, @7 t! k) Z7 J$ o2 O}$ S) K6 h$ m: t2 c
if (e.commandname == down)7 {3 L2 |2 ^# t7 x' o' O
{
W2 l m) i7 o$ `1 C$ [try
0 \7 [! X& d" m, M{: G+ L2 Y" M" `7 c
string downloadfilename = ~/uploads/ + e.commandargument.tostring();//文件路径7 W' g% r6 F5 w% M+ D! F% Y
string filepath = server.mappath(downloadfilename);* F( l" T0 F9 p8 r8 j; B- Q
string filename = path.getfilename(filepath);1 W8 A* R1 r+ r2 Q9 i6 R/ m
fileinfo file = new fileinfo(filepath);
& w1 C& a" ~1 R, vresponse.clear();2 ~* t# \9 x2 K( a. F: q) N1 F
response.contenttype = application/octet-stream;
\( \0 U+ L; v, rresponse.addheader(content-disposition, attachment; filename= + httputility.urlencode(filename, system.text.encoding.utf8));
* q2 h% K" ?. V# k7 ]! R. qresponse.addheader(content-length, file.length.tostring());+ J- z% H! I( I7 v% M/ P1 a
response.flush();
4 U% s# R( k% Z; `6 }8 {" o& O0 Sresponse.writefile(filepath);3 g& G+ ^) E7 `( U; k! }
}+ R( E; w4 _% T" _; v% I
catch
8 b1 a: I" v# u2 V( q5 {{
3 g( N1 \% D6 U/ [3 M3 Q0 S2 ]' {response.write(<script>alert('没有找到下载的源文件')</script>);4 o; m' R1 @3 S" n/ F
}. N2 h( f" M2 i; ~, g' O
}: V7 M# V( z) Z, J
希望本文所述对大家的asp.net程序设计有所帮助。
1 I1 S, w" {: w6 B# S
$ w5 q2 }$ j. X* \# t( S# x5 p更多网页制作信息请查看: 网页制作 |