2011年11月10日 星期四

將FileInfo物件的長度(檔案大小)轉為 KB字串

using System.Globalization;

protected string FormatSize(long lSize)
        {
            //格式化數字為 KB
            string stringSize = "";
            NumberFormatInfo myNfi = new NumberFormatInfo();

            long lKBSize = 0;

            if (lSize < 1024)
            {
                if (lSize == 0)
                {
                    //零位元組
                    stringSize = "0";
                }
                else
                {
                    //小於 1K 但不為零位元組
                    stringSize = "1";
                }
            }
            else
            {
                //轉換為KB
                lKBSize = lSize / 1024;
                //用預設格式來格式化數字
                stringSize = lKBSize.ToString("n", myNfi);
                //移除十進制
                stringSize = stringSize.Replace(".00", "");
            }

            return stringSize + " KB";

        }
之後你就可以用下面這行來呼叫它:
FormatSize(new FileInfo(fileName).length);

沒有留言: