此文记录的是一个将字节大小的值转换为KB、MB等显示的小函数。
/***
字节显示转换操作类
Austin Liu 刘恒辉
Project Manager and Software Designer
E-Mail: lzhdim@163.com
Blog: http://lzhdim.cnblogs.com
Date: 2024-01-15 15:18:00
使用说明:
KeyValuePair<string, double> m_kv = ConvertUtil.HtConvertByteUnit(size);
string sizes = m_kv.Value + " " + m_kv.Key;
***/
namespace Lzhdim.LPF.Utility
{
using System;
using System.Collections.Generic;
/// <summary>
/// 字节显示转换操作类
/// </summary>
public static class ConvertUtil
{
/// <summary>
/// byte转换为GB/MB/KB
/// </summary>
/// <param name="KSize"></param>
/// <returns></returns>
public static KeyValuePair<string, double> HtConvertByteUnit(long KSize)
{
KeyValuePair<string, double> m_kv;// = new KeyValuePair<string, double>();
int m_GB = 1024 * 1024 * 1024;//定义GB的计算常量
int m_MB = 1024 * 1024;//定义MB的计算常量
int m_KB = 1024;//定义KB的计算常量
if (KSize / m_GB >= 1)//如果当前Byte的值大于等于1GB
{
m_kv = new KeyValuePair<string, double>("GB", Math.Round(KSize / (float)m_GB, 2));
//将其转换成GB
}
else if (KSize / m_MB >= 1)//如果当前Byte的值大于等于1MB
{
m_kv = new KeyValuePair<string, double>("MB", Math.Round(KSize / (float)m_MB, 2));
//将其转换成MB
}
else if (KSize / m_KB >= 1)//如果当前Byte的值大于等于1KB
{
m_kv = new KeyValuePair<string, double>("KB", Math.Round(KSize / (float)m_KB, 2));
//将其转换成KB
}
else
{
m_kv = new KeyValuePair<string, double>("Byte", KSize);
//显示Byte值
}
return m_kv;
}
}
}