首页 > 代码库 > [C#]读取文件大小
[C#]读取文件大小
关键代码:
/// <summary> /// 获取文件大小—字节 /// </summary> /// <param name="filePath">文件路径</param> /// <returns>文件大小</returns> public static long GetSize(string filePath) { long _size = 0; try { if (File.Exists(filePath)) { FileStream _stream = new FileStream(filePath, FileMode.Open); _size = _stream.Length; _stream.Close(); _stream.Dispose(); } } catch (Exception ex) { _size = 0; Debug.WriteLine(string.Format("获取文件大小异常,原因:{0}", ex.Message)); } return _size; } /// <summary> /// 获取文件大小—kb /// </summary> /// <param name="filePath">文件路径</param> /// <returns>文件大小_kb</returns> public static double GetKBSize(string filePath) { double _kb = 0; long _size = GetSize(filePath); if (_size != 0) { _kb = _size / 1024d; } return _kb; } /// <summary> /// 获取文件大小—mb /// </summary> /// <param name="filePath">文件路径</param> /// <returns>文件大小_mb</returns> public static double GetMBSize(string filePath) { double _mb = 0; long _size = GetSize(filePath); if (_size != 0) { _mb = _size / 1048576d;//1024*1024==1048576; } return _mb; }代码比较简单,那么我们来测试一下,有一个一兆多日志文件,来读取下,如图:
测试代码:
string _path = @"C:\CodePlex\CSharpUtilHelp\UtilHelp\LogUtilHelpV2Test\bin\Release\Log\20140731.log"; Console.WriteLine("File Size:" + FileToolV2.GetSize(_path)); Console.WriteLine("File Size_kb:" + FileToolV2.GetKBSize(_path) + " kb"); Console.WriteLine("File Size_mb:" + FileToolV2.GetMBSize(_path) + " mb");
测试效果:
希望有所帮助!
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style><style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。