C# Bytes, KB, MD, GB 변환하기 0.00형식으로

2019. 6. 14. 10:59C#

728x90
반응형

 

 

바이트로 되어있는 것을 KB, MB, GB 형식으로 변환 해주는 것

 

ListView에 아이템을 추가하는 코드

// 리스트뷰에 아이템 추가할 때 
for (int i = 0; i < files.Length; i++)
{
    System.IO.FileInfo flinfo = new System.IO.FileInfo(files[i]);

    ListViewItem item = new ListViewItem(flinfo.Name, 0);       // 파일 명

    // 형변환하여 파일크기 지정
    long aSize = Convert.ToInt64(flinfo.Length.ToString()); 
    item.SubItems.Add(FormatBytes(aSize));                    // 파일 크기
   
    item.SubItems.Add(flinfo.Extension.ToString());                // 파일 종류 (확장자)
    item.SubItems.Add(flinfo.LastAccessTime.ToString());        // 파일 마지막 수정날짜
    item.SubItems.Add(flinfo.FullName.ToString());                  // 경로

    listView1.Items.Add(item);
}

 

 

FormatBytes() 를 이용하여 용량형식을 변경해줍니다.


// 변환 해주는 함수
public string FormatBytes(long bytes)
{
    const int scale = 1024;
    string[] orders = new string[] { "GB", "MB", "KB", "Bytes" };
    long max = (long)Math.Pow(scale, orders.Length - 1);

    foreach (string order in orders)
    {
        if (bytes > max)
            return string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order);

        max /= scale;
    }
    return "0 Bytes";
}

 

 

728x90
반응형