[C#]讀取檔案大小

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   檔案   for   

關鍵代碼:

        /// <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");

測試效果:

希望有所協助!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.