web 2.0

How-To Get Human Friendly File Size With C#

Hi,

In this article I’ll provide a simple way to Display Human Friendly File Sizes with C#.

In order to do that I created a simple Class Called FriendlySize.

FriendlySize

public class FriendlySize
{
    #region Private Fields

    private long _length;
    private String[] _sizes = { "B", "KB", "MB", "GB" };

    #endregion

    #region Constructors

    public FriendlySize(FileInfo file)
    {
        _length = file.Length;
    }
    public FriendlySize(String file)
        : this(new FileInfo(file))
    {
    }
    public FriendlySize(long size)
    {
        _length = size;
    }

    #endregion

    #region Public Overrides Methods

    public override string ToString()
    {
        double len = _length;
        int order = 0;
        while (len >= 1024 && order + 1 < _sizes.Length)
        {
            order++;
            len = len / 1024;
        }
        return String.Format("{0:0.##} {1}", len, _sizes[order]);
    }

    #endregion
}

Sample Usage :

string path = @"C:\test.zip";
FriendlySize size = new FriendlySize(path);
Console.WriteLine(size);

Output :

1,17 KB

 

Hope this help’s!.



Views(1706)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile