C#获取文件、文件夹大小

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

·½·¨Ò»£ºOpenFileDialogop1=newOpenFileDialog();if(op1.ShowDialog()==DialogResult.OK){FileInfofi=newFileInfo(op1.FileName);this.Text=(fi.Length/1024).ToString()+kb;}·½·¨¶þ£º//ÓÃDirectoryInfo.GetFiles¿ÉÒÔ»ñµÃËùÓÐÎļþ£¬´óС¿ÉÒÔÓÃFileInfo.Legth»ñµÃpublicstaticfloatlength=0;//Îļþ×Ü´óСpublicintdirNum=0;//ÎļþĿ¼¸öÊýpublicintfileNum=0;//Îļþ¸öÊý//°ó¶¨Îļþ´óСpublicvoidbinder(){stringfileName=Server.MapPath(Dir/+Session[UserName].ToString());length=Convert.ToSingle(GetDirectoryLength(fileName));stringsize=0;if(length1024){size=string.Format({0:N0},length)+B;}elseif(length1024){if(length1048576){size=string.Format({0:N1},length/1024)+KB;}else{size=string.Format({0:N2},length/1048576)+MB;}}Response.Write(size);}//»ñÈ¡Îļþ¼Ð´óС×ܺÍpubliclongGetDirectoryLength(stringdirPath){//Åжϸø¶¨µÄ·¾¶ÊÇ·ñ´æÔÚ,Èç¹û²»´æÔÚÔòÍ˳öif(!Directory.Exists(dirPath))return0;longlen=0;//Ŀ¼Îļþ´óС×ܺÍ//¶¨ÒåÒ»¸öDirectoryInfo¶ÔÏóDirectoryInfodi=newDirectoryInfo(dirPath);//ͨ¹ýGetFiles·½·¨,»ñÈ¡diĿ¼ÖеÄËùÓÐÎļþµÄ´óСforeach(FileInfofiindi.GetFiles()){len+=fi.Length;}fileNum+=di.GetFiles().Length;//»ñÈ¡diÖÐËùÓеÄÎļþ¼Ð,²¢´æµ½Ò»¸öеĶÔÏóÊý×éÖÐ,ÒÔ½øÐеݹéDirectoryInfo[]dis=di.GetDirectories();dirNum+=dis.Length;if(dis.Length0){for(inti=0;idis.Length;i++){len+=GetDirectoryLength(dis[i].FullName);}}returnlen;}·½·¨Èý£º//C#»ñÈ¡Îļþ´óС£¬µ±È»Á˶¼ÐèÒªÒýÈëSystem.IOÕâ¸öÃüÃû¿Õ¼äµÚÒ»¸ö:publicstaticlongGetDirectoryLength(stringdirPath){//Åжϸø¶¨µÄ·¾¶ÊÇ·ñ´æÔÚ,Èç¹û²»´æÔÚÔòÍ˳öif(!Directory.Exists(dirPath))return0;longlen=0;//¶¨ÒåÒ»¸öDirectoryInfo¶ÔÏóDirectoryInfodi=newDirectoryInfo(dirPath);//ͨ¹ýGetFiles·½·¨,»ñÈ¡diĿ¼ÖеÄËùÓÐÎļþµÄ´óСforeach(FileInfofiindi.GetFiles()){len+=fi.Length;}//»ñÈ¡diÖÐËùÓеÄÎļþ¼Ð,²¢´æµ½Ò»¸öеĶÔÏóÊý×éÖÐ,ÒÔ½øÐеݹéDirectoryInfo[]dis=di.GetDirectories();if(dis.Length0){for(inti=0;idis.Length;i++){len+=GetDirectoryLength(dis[i].FullName);}}returnlen;}µÚ¶þ¸ö//Ò²ÊÇÀûÓõݹéµÄ˼Ïë,Ö»²»¹ýÊÇͨ¹ýFileÀàµÄExits·½·¨À´ÅжÏ//Ëù¸ø·¾¶ÖÐËù¶ÔÓ¦µÄÊÇ·ñΪÎļþpublicstaticlongFileSize(stringfilePath){longtemp=0;//Åжϵ±Ç°Â·¾¶ËùÖ¸ÏòµÄÊÇ·ñΪÎļþif(File.Exists(filePath)==false){string[]str1=Directory.GetFileSystemEntries(filePath);foreach(strings1instr1){temp+=FileSize(s1);}}else{//¶¨ÒåÒ»¸öFileInfo¶ÔÏó,ʹ֮ÓëfilePathËùÖ¸ÏòµÄÎļþÏò¹ØÁª,//ÒÔ»ñÈ¡Æä´óСFileInfofileInfo=newFileInfo(filePath);returnfileInfo.Length;}returntemp;}

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功