Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created June 9, 2017 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/613b48a0af6a56ac4b7c2c327f0f147c to your computer and use it in GitHub Desktop.
Save wolf99/613b48a0af6a56ac4b7c2c327f0f147c to your computer and use it in GitHub Desktop.
A ToString() extension to the System.Version class, that allows specification of padding of the version parts
Option Strict On
Option Explicit On
Imports System.Text
Imports System.Runtime.CompilerServices
Module PaddedVersionToString
''' <summary>
''' Converts the value of the current Version object to its equivalent
''' String representation. Specified counts indicate the number of
''' components to return and the padding of the components.
''' </summary>
''' <param name="fieldCount">The number of components to return. The
''' fieldCount ranges from 0 to 4.</param>
''' <param name="fieldPadding">The number of padding characters for each
''' component.</param>
''' <returns>
''' The String representation of the values of the major, minor, build, and
''' revision components of the current Version object, each separated by a
''' period character ('.'). The fieldCount parameter determines how many
''' components are returned. The fieldPadding parameter determines the
''' number of padding characters used by each component
''' </returns>
<Extension()> Public Function ToString(version As Version,
fieldCount As Integer,
fieldPadding As Integer) As String
Dim Builder As StringBuilder = New StringBuilder()
' Convert the version to a string and split the result at the version
' delimiter (i.e. ".")
Dim Parts As String() = version.ToString(fieldCount).Split("."c)
If fieldCount = 0 Then
Return String.Empty ' No parts so no string
ElseIf fieldCount = 1 Then
' Single part with padding and without trailing delimiter
Builder.Append(Parts(0).PadLeft(fieldPadding, "0"c))
Else ' fieldCount >= 2
For i As Integer = 0 To fieldCount - 2
' All but last part with padding and trailing delimiter
Builder.AppendFormat("{0}.", Parts(i).PadLeft(fieldPadding, "0"c))
Next
' Final part with padding and without trailing delimiter
Builder.AppendFormat("{0}", Parts(fieldCount - 1).PadLeft(fieldPadding, "0"c))
End If
Return Builder.ToString()
End Function
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment