I want to allow a user to enter a file size, using any of the standard suffixes (such as TB, MB, GB)
I'd like to get the value in a way that i can compare them to a folder size.
The idea is to have a program that'll warn if a folder gets above a certain size, with the size dictated by a user-inputted string.
Is there anything built into the .net framework that allows me to parse strings such as 1.5TB
, 400GB
, 1.9GB
and 0.5KB
?
This is a good candidate for a simple Interpreter.
Code like this is a simple start, you will need to handle perhaps more cases, and account for differences in casing (
Gb
vsGB
for example).You start with a definition for a context and an Expression:
Then you define your terminal expression,a nd all of the variants:
Then you add a non-terminal expression (this does the bulk of the work):
Finally, here is the sort of client code:
Live example: http://rextester.com/rundotnet?code=WMGOQ13650
Edits. Changed to MB from Mb (one is officially MegaByte other is MegaBit). Changed int to long to account for large sizes.
I couldn't find functionality like this in the .NET Framework with a quick Google search, so I guess it's up to you to implement it.
I think splitting the string on numeric values and a dot (or comma, think international) as first part and extracting the KB/MB/etc as second part and parse each part manually will be the way to go.
Short answer: no, there is no built in method.
Long answer: use my converter.
EDIT: here's live demonstration: http://rextester.com/rundotnet?code=BQYCB2587 (thanks @Jamiec for the link, really handy to run C# source online)