@@ -66,21 +66,84 @@ public static string FormatNumber(string value)
6666 {
6767 return string . Format ( "{0:n0}" , Convert . ToInt32 ( value ) ) ;
6868 }
69-
69+
70+ private static string [ ] SizeSuffixes = { "Bytes" , "KB" , "MB" , "GB" , "TB" , "PB" , "EB" , "ZB" , "YB" } ;
71+
7072 /// <summary>
7173 /// Return file size with suffix e.g. Bytes, MB, GB
7274 /// </summary>
7375 /// <param name="byteCount"></param>
7476 /// <returns>Bytes in string format</returns>
75- public static String BytesToPrefix ( long byteCount )
77+ public static string BytesToPrefix ( long byteCount )
7678 {
77- string [ ] suf = { "Bytes" , "KB" , "MB" , "GB" , "TB" , "PB" , "EB" } ; // Longs run out around EB
7879 if ( byteCount == 0 )
79- return "0" + " " + suf [ 0 ] ;
80+ return "0" + " " + SizeSuffixes [ 0 ] ;
8081 long bytes = Math . Abs ( byteCount ) ;
8182 int place = Convert . ToInt32 ( Math . Floor ( Math . Log ( bytes , 1024 ) ) ) ;
8283 double num = Math . Round ( bytes / Math . Pow ( 1024 , place ) , 1 ) ;
83- return ( Math . Sign ( byteCount ) * num ) . ToString ( ) + " " + suf [ place ] ;
84+ return ( Math . Sign ( byteCount ) * num ) . ToString ( ) + " " + SizeSuffixes [ place ] ;
85+ }
86+
87+ /// <summary>
88+ /// Returns the total number of bytes from parsing the size prefix
89+ /// </summary>
90+ /// <param name="value"></param>
91+ /// <returns></returns>
92+ public static long ParseFileSize ( string prefixSize )
93+ {
94+ // Remove leading and trailing spaces.
95+ prefixSize = prefixSize . Trim ( ) ;
96+
97+ try
98+ {
99+ // Find the last non-alphabetic character.
100+ int ext_start = 0 ;
101+ for ( int i = prefixSize . Length - 1 ; i >= 0 ; i -- )
102+ {
103+ // Stop if we find something other than a letter.
104+ if ( ! char . IsLetter ( prefixSize , i ) )
105+ {
106+ ext_start = i + 1 ;
107+ break ;
108+ }
109+ }
110+
111+ // Get the numeric part.
112+ double number = double . Parse ( prefixSize . Substring ( 0 , ext_start ) ) ;
113+
114+ // Get the extension.
115+ string suffix ;
116+ if ( ext_start < prefixSize . Length )
117+ {
118+ suffix = prefixSize . Substring ( ext_start ) . Trim ( ) ;
119+ if ( suffix == "BYTES" ) suffix = "Bytes" ;
120+ }
121+ else
122+ {
123+ suffix = "Bytes" ;
124+ }
125+
126+ // Find the extension in the list.
127+ int suffix_index = - 1 ;
128+ for ( int i = 0 ; i < SizeSuffixes . Length ; i ++ )
129+ {
130+ if ( SizeSuffixes [ i ] == suffix )
131+ {
132+ suffix_index = i ;
133+ break ;
134+ }
135+ }
136+ if ( suffix_index < 0 )
137+ throw new FormatException (
138+ "Unknown file size prefix " + suffix + "." ) ;
139+
140+ // Return the result.
141+ return ( long ) Math . Round ( number * Math . Pow ( 1024 , suffix_index ) ) ;
142+ }
143+ catch ( Exception ex )
144+ {
145+ throw new FormatException ( "Invalid file size format" , ex ) ;
146+ }
84147 }
85148
86149 /// <summary>
0 commit comments