Home
Manage Your Code
Snippet: File Size as String - Better version (C#)
Title: File Size as String - Better version Language: C#
Description: This function will return the file size in string. Views: 118
Author: Peter Petrov Date Added: 7/18/2008
Copy Code  
1        public static string GetFileSize(long totalBytes)
2        {
3            string formattedSize = "0 Bytes";
4
5            if (totalBytes > 0)
6            {
7                var KB = 1024;
8                var MB = KB * KB;
9                var GB = MB * KB;
10                var formatTemplate = @"{0:##.##}";
11                if (totalBytes < KB)
12                {
13                    formattedSize = string.Format(formatTemplate, totalBytes) + " Bytes";
14                }
15                else if (totalBytes < MB)
16                {
17                    formattedSize = string.Format(formatTemplate, totalBytes / KB) + " KB";
18                }
19                else if (totalBytes < GB)
20                {
21                    formattedSize = string.Format(formatTemplate, totalBytes / MB) + " MB";
22                }
23                else
24                {
25                    formattedSize = string.Format(formatTemplate, totalBytes / GB) + " GB";
26                }
27            }
28            return formattedSize;
29        }
Usage
var size = GetFileSize(new FileInfo(@"some filename").Length);
Notes
Yesterday my Indian (I suggest from his name) "friend" Pragnesh Patel posted the initial version of this method but when I've looked at the code it was just crap. It's a mix of very long if/else if chain, some hard coded indexes and values, inappropriate use of string instead of long and very poor understanding of the problem.