Class for converting & formatting bytes, kilobytes, megabytes, gigabytes, etc.

by doug 14. May 2009 04:14

I'm working on an application that reads files from user selected folders and displays the names and file sizes in a grid.  I want the file sizes to be formatted appropriate to their size.  For example if a file is 50 bytes in size, it should say "50 B."  If it's 200,000 bytes, it should be displayed as "195.3 KB."  If it's 2,000,000 bytes, it should be displayed as "1.9 MB."

So I created the class displayed below.  Instantiate it by passing in the number you want to convert and identifying what unit that number is in.  Then if you know ahead of time what unit you want to convert that number to, call the relevant property.  For example if you want to output in Megabytes, call the Megabytes() property.  Or, as in my case, if you want it to automatically determine the best unit to output as, call the AutoUnit() property.

Here's an example of how you could use it:

Dim Label1 As New Label

Dim myFileInfo As New System.IO.FileInfo("c:\testfile.jpg")

Dim myUnitConvert As New _

cDataUnitConversions(cDataUnitConversions.DataUnits.Bytes, _

myFileInfo.Length)

Label1.Text = myUnitConvert.AutoUnit

The FileInfo class is used to get the attributes of the file "testfile.jpg."  Then the cDataUnitConverstions class is instantiated, passing in the length of the test file and identifying that length as being in Bytes.  From there the Label1.Text property is set to be equal to the AutoUnit value, which would be something like "345.12 KB" depending on how big the test file really is.

Below is the class.  Some next steps would include expanding it to output as strings or numeric data types, toggle on or off the unit labels in the string (like "50 MB" vs. "50"), and more.  But hopefully this will get you going in the right direction and you can customize as you see fit.

Public Class cDataUnitConversions

 

#Region " Enums, Global Variables and Constants "

 

  Public Enum DataUnits

    Bits

    Bytes

    Kilobytes

    Megabytes

    Gigabytes

    Terabytes

  End Enum

 

  Dim _inputValue As Double

  Dim _inputUnit As DataUnits

 

  Const BitsInByte As Double = 8

  Const BytesInKilobyte As Double = 1024

  Const BytesInMegabyte As Double = 1048576

  Const BytesInGigabyte As Double = 1073741824

  Const BytesInTerabyte As Double = 1099511627776

 

#End Region

 

#Region " Properties "

 

  Public ReadOnly Property Bits() As String

    Get

      Return String.Format("{0:N}", _

      InputAsBytes() * BitsInByte) & " b"

    End Get

  End Property

 

  Public ReadOnly Property Bytes() As String

    Get

      Return String.Format("{0:N}", InputAsBytes()) & " B"

    End Get

  End Property

 

  Public ReadOnly Property Kilobytes() As String

    Get

      Return String.Format("{0:N}", _

      InputAsBytes() / BytesInKilobyte) & " KB"

    End Get

  End Property

 

  Public ReadOnly Property Megabytes() As String

    Get

      Return String.Format("{0:N}", _

      InputAsBytes() / BytesInMegabyte) & " MB"

    End Get

  End Property

 

  Public ReadOnly Property Gigabytes() As String

    Get

      Return String.Format("{0:N}", _

      InputAsBytes() / BytesInGigabyte) & " GB"

    End Get

  End Property

 

  Public ReadOnly Property Terabytes() As String

    Get

      Return String.Format("{0:N}", _

      InputAsBytes() / BytesInTerabyte) & " TB"

    End Get

  End Property

 

  Public ReadOnly Property AutoUnit() As String

    Get

      Return GetAutoUnit()

    End Get

  End Property

 

#End Region

 

#Region " Public Methods "

 

  Public Sub New(ByVal inputUnit As DataUnits, _

  ByVal inputValue As Double)

 

    _inputValue = inputValue

    _inputUnit = inputUnit

 

  End Sub

 

#End Region

 

#Region " Private Methods "

 

  Private Function GetAutoUnit() As String

 

    Dim Output As String

    Dim InputBytes As Double = InputAsBytes()

 

    Select Case InputBytes

 

      Case Is < BytesInKilobyte

        Output = String.Format("{0:N}", _

        InputBytes * BitsInByte) & " B"

 

      Case Is < BytesInMegabyte

        Output = String.Format("{0:N}", _

        InputBytes / BytesInKilobyte) & " KB"

 

      Case Is < BytesInGigabyte

        Output = String.Format("{0:N}", _

        InputBytes / BytesInMegabyte) & " MB"

 

      Case Is < BytesInTerabyte

        Output = String.Format("{0:N}", _

        InputBytes / BytesInGigabyte) & " GB"

 

      Case Is >= BytesInTerabyte

        Output = String.Format("{0:N}", _

        InputBytes / BytesInTerabyte) & " TB"

 

      Case Else

        Output = _inputValue

 

    End Select

 

    Return Output

  End Function

 

  Private Function InputAsBytes() As Double

 

    Dim InputBytes As Double

 

    Select Case _inputUnit

 

      Case DataUnits.Bits

        InputBytes = _inputValue / BitsInByte

 

      Case DataUnits.Bytes

        InputBytes = _inputValue

 

      Case DataUnits.Kilobytes

        InputBytes = _inputValue * BytesInKilobyte

 

      Case DataUnits.Megabytes

        InputBytes = _inputValue * BytesInMegabyte

 

      Case DataUnits.Gigabytes

        InputBytes = _inputValue * BytesInGigabyte

 

      Case DataUnits.Terabytes

        InputBytes = _inputValue * BytesInTerabyte

 

      Case Else

        InputBytes = -1

 

    End Select

 

    Return InputBytes

 

  End Function

 

#End Region

 

End Class

Tags:

Extract E-mail Address from Block of Text

by doug 3. May 2009 20:50

On one of my projects I periodically need to extract a bunch of e-mail addresses from messages that are forwarded to me.  Those forwarded messages aren't always very cleanly formatted, meaning that before I'm able to produce a list of just the e-mail addresses I've been having to manually go through all the text and remove what I don't need, copy out the parts I want, etc... a process insiders call "the wrong way."

So I created a web form that lets me paste in my source text into a multiline textbox, click a button and it returns a comma separated list of e-mail address pulled from the text.  The core of this process is found in the following function using regular expressions:

Private Function GetEmails(ByVal text As String) As String

 

  Dim output As String = ""

  Dim pattern As String = _

    "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"

  Dim re As New Regex(pattern, RegexOptions.IgnoreCase)

  Dim matches As MatchCollection = re.Matches(text)

  Dim myMatch As Match

 

  For Each myMatch In matches

    output &= myMatch.ToString.ToLower & ","

  Next

 

  Return output.Trim(","c)

 

End Function

Here's what's going on:

  1. Pass into the function the block of messy text that contains the e-mail address you're looking for (textBlock)
  2. The "pattern" variable is string used to describe to the regex engine what an e-mail address looks like (thanks to the folks over at Regular-Expressions.info for this one!)
  3. Create a regex object (re) using the pattern string, and in this context we need to set the option to ignore case.
  4. Create a MatchCollection object to hold all the e-mail address matches found, then get the matches... = re.Matches(textBlock)
  5. In my case I wanted a comma separated list of e-mail addresses, so I iterated through the matches and appended a comma after each instance.
  6. Output the comma separated list, trimming off the last trailing comma.

The beauty of this is it's a small amount of code and very flexible.  You're not dependent on the block of text being formatted in any particular way, meaning you don't have to do any clean up ahead of time.  Just copy the source block of text, paste it into the form, click submit and it runs through the function and your list is spit out on the other end.

Tags:

VB.Net

Welcome to BlogEngine.NET 1.5.0

by Administrator 2. April 2009 09:00

If you see this post it means that BlogEngine.NET 1.5.0 is running and the hard part of creating your own blog is done. There is only a few things left to do.

Write Permissions

To be able to log in to the blog and writing posts, you need to enable write permissions on the App_Data folder. If you’re blog is hosted at a hosting provider, you can either log into your account’s admin page or call the support. You need write permissions on the App_Data folder because all posts, comments, and blog attachments are saved as XML files and placed in the App_Data folder. 

If you wish to use a database to to store your blog data, we still encourage you to enable this write access for an images you may wish to store for your blog posts.  If you are interested in using Microsoft SQL Server, MySQL, VistaDB, or other databases, please see the BlogEngine wiki to get started.

Security

When you've got write permissions to the App_Data folder, you need to change the username and password. Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it. Now enter "admin" in both the username and password fields and click the button. You will now see an admin menu appear. It has a link to the "Users" admin page. From there you can change the username and password.  Passwords are hashed by default so if you lose your password, please see the BlogEngine wiki for information on recovery.

Configuration and Profile

Now that you have your blog secured, take a look through the settings and give your new blog a title.  BlogEngine.NET 1.4 is set up to take full advantage of of many semantic formats and technologies such as FOAF, SIOC and APML. It means that the content stored in your BlogEngine.NET installation will be fully portable and auto-discoverable.  Be sure to fill in your author profile to take better advantage of this.

Themes and Widgets

One last thing to consider is customizing the look of your blog.  We have a few themes available right out of the box including two fully setup to use our new widget framework.  The widget framework allows drop and drag placement on your side bar as well as editing and configuration right in the widget while you are logged in.  Be sure to check out our home page for more theme choices and downloadable widgets to add to your blog.

On the web

You can find BlogEngine.NET on the official website. Here you'll find tutorials, documentation, tips and tricks and much more. The ongoing development of BlogEngine.NET can be followed at CodePlex where the daily builds will be published for anyone to download.

Good luck and happy writing.

The BlogEngine.NET team

Tags: ,

BlogEngine.NET

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen