C#将数据大小字节转换为MB,GB,TB

方法挺简单,但是写起来麻烦,留着备用….

下面放演示…

转换类

/*
 * By: 落落
 * URL: Www.MyLuoLuo.Com
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace ConvertDataSize
{
    public class Convert
    {
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public string GetSize(long b)
        {
            if (b.ToString().Length <= 10)
                return GetMB(b);
            if (b.ToString().Length >= 11 && b.ToString().Length <=12)
                return GetGB(b);
            if (b.ToString().Length >= 13)
                return GetTB(b);
            return String.Empty;
        }

        /// <summary>
        /// 将B转换为TB
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private string GetTB(long b)
        {
            for (int i = 0; i < 4; i++)
            {
                b /= 1024;
            }
            return b + "TB";
        }

        /// <summary>
        /// 将B转换为GB
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private string GetGB(long b)
        {
            for (int i = 0; i < 3; i++)
            {
                b /= 1024;
            }
            return b + "GB";
        }

        /// <summary>
        /// 将B转换为MB
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private string GetMB(long b)
        {
            for (int i = 0; i < 2; i++)
            {
                b /= 1024;
            }
            return b + "MB";
        }
    }
}

示例程序:

ConvertDataSize.zip(124.3 KB, 56 次)

 

2 Replies to “C#将数据大小字节转换为MB,GB,TB”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据