Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 4 Visitantes están viendo este tema.

z3nth10n

Bueno, como siempre se agradecen sugerencias... Acabo de editar el código y sí, ese indentador no es mio, y la verdad es que tampoco me preocupe mucho, como vi que funciono la primera vez pues no le presté mucha atención...

Ahora como verás me he pasado poniendo usings, pero bueno >:D

Interesados hablad por Discord.

Eleкtro

#411
Cita de: Ikillnukes en  8 Agosto 2014, 21:07 PMcomo vi que funciono la primera vez pues no le presté mucha atención...

Funciona a la primera según se mire, ya que el que escribió ese snippet definió el uso de la codificación UTF-16 (Encoding.Unicode) para todos los casos.

Cita de: Ikillnukes en  8 Agosto 2014, 21:07 PMAhora como verás me he pasado poniendo usings, pero bueno >:D

No te has pasado, has echo lo correcto (me refiero a corregir los fallos del código, aparte de tener que escuchar mi típico sermón xD)

Saludos








Eleкtro

Como partir un archivo en pequeños trozos de cualuier tamaño (no hay limite de 2 GB).

Código (vbnet) [Seleccionar]
    ' Split File
    ' By Elektro
    '
    ' Example Usage:
    ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)

    ''' <summary>
    ''' Splits a file into chunks.
    ''' </summary>
    ''' <param name="InputFile">
    ''' Indicates the input file to split.
    ''' </param>
    ''' <param name="ChunkSize">
    ''' Indicates the size of each chunk.
    ''' </param>
    ''' <param name="ChunkName">
    ''' Indicates the chunk filename format.
    ''' Default format is: 'FileName.ChunkIndex.FileExt'
    ''' </param>
    ''' <param name="ChunkExt">
    ''' Indicates the chunk file-extension.
    ''' If this value is <c>Null</c>, the input file-extension will be used.
    ''' </param>
    ''' <param name="Overwrite">
    ''' If set to <c>true</c>, chunk files will replace any existing file;
    ''' Otherwise, an exception will be thrown.
    ''' </param>
    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
    ''' <exception cref="System.IO.IOException"></exception>
    Public Sub SplitFile(ByVal InputFile As String,
                         ByVal ChunkSize As Long,
                         Optional ByVal ChunkName As String = Nothing,
                         Optional ByVal ChunkExt As String = Nothing,
                         Optional ByVal Overwrite As Boolean = False)

        ' FileInfo instance of the input file.
        Dim fInfo As New IO.FileInfo(InputFile)

        ' The buffer to read data and write the chunks.
        Dim Buffer As Byte() = New Byte() {}

        ' The buffer length.
        Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb

        ' Counts the length of the current chunk file.
        Dim BytesWritten As Long = 0L

        ' The total amount of chunks to create.
        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))

        ' Keeps track of the current chunk.
        Dim ChunkIndex As Integer = 0I

        ' A zero-filled string to enumerate the chunk files.
        Dim Zeros As String = String.Empty

        ' The given filename for each chunk.
        Dim ChunkFile As String = String.Empty

        ' The chunk file basename.
        ChunkName = If(String.IsNullOrEmpty(ChunkName),
                       IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
                       IO.Path.Combine(fInfo.DirectoryName, ChunkName))

        ' The chunk file extension.
        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
                      fInfo.Extension.Substring(1I),
                      ChunkExt)

        ' If ChunkSize is bigger than filesize then...
        If ChunkSize >= fInfo.Length Then
            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
            Exit Sub

            ' For cases where a chunksize is smaller than the buffersize.
        ElseIf ChunkSize < BufferSize Then
            BufferSize = CInt(ChunkSize)

        End If ' ChunkSize <>...

        ' If not file-overwritting is allowed then...
        If Not Overwrite Then

            For Index As Integer = 0I To (ChunkCount)

                ' Set chunk filename.
                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)

                ' If chunk file already exists then...
                If IO.File.Exists(ChunkFile) Then

                    Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
                    Exit Sub

                End If ' IO.File.Exists(ChunkFile)

            Next Index

            Zeros = String.Empty
            ChunkFile = String.Empty

        End If ' Overwrite

        ' Open the file to start reading bytes.
        Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)

            Using BinaryReader As New IO.BinaryReader(InputStream)

                While (InputStream.Position < InputStream.Length)

                    ' Set chunk filename.
                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)

                    ' Reset written byte-length counter.
                    BytesWritten = 0L

                    ' Create the chunk file to Write the bytes.
                    Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)

                        Using BinaryWriter As New IO.BinaryWriter(OutputStream)

                            ' Read until reached the end-bytes of the input file.
                            While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                                ' Read bytes from the original file (BufferSize byte-length).
                                Buffer = BinaryReader.ReadBytes(BufferSize)

                                ' Write those bytes in the chunk file.
                                BinaryWriter.Write(Buffer)

                                ' Increment the size counter.
                                BytesWritten += Buffer.Count

                            End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                            OutputStream.Flush()

                        End Using ' BinaryWriter

                    End Using ' OutputStream

                    ChunkIndex += 1I 'Increment file counter

                End While ' InputStream.Position < InputStream.Length

            End Using ' BinaryReader

        End Using ' InputStream

    End Sub








Eleкtro

una Helper-Class para procesar los pixeles de una imagen, buscar un color especifico y devolver las coordenadas, obtener un rango de píxeles, etc.

Código (vbnet) [Seleccionar]

' ***********************************************************************
' Author           : Elektro
' Last Modified On : 07-11-2014
' ***********************************************************************
' <copyright file="PixelUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "


' **************************************************
' Count the number of Pixels that contains the image
' **************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Display the pixel count.
'MessageBox.Show(String.Format("Total amount of Pixels: {0}", CStr(bmpPixelUtil.PixelCount)))


' ************************************************
' Searchs for an specific pixel color in the image
' ************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Specify the RGB PixelColor to search.
'Dim FindColor As Color = Color.FromArgb(255, 174, 201)
'
'' Get the pixel data.
'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.SearchColor(FindColor)
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In FoundPixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel-Color Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


' *********************************************************************
' Retrieve the index, color, and coordinates of each pixel in the image
' *********************************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Get the pixel data.
'Dim Pixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData()
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In Pixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


' ****************************************************************************
' Retrieve the index, color, and coordinates of a range of pixels in the image
' ****************************************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Specify the pixel range to retrieve.
'Dim RangeMin As Integer = 1919I
'Dim RangeMax As Integer = 1921I
'
'' Get the pixel data.
'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData(RangeMin, RangeMax)
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In FoundPixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel-Color Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices

#End Region

#Region " PixelUtil "

Public Class PixelUtil

#Region " Vars, Properties "

   Private _PixelData As List(Of PixelData) = Nothing
   Private _bmp As Bitmap = Nothing
   Private _PixelCount As Integer = Nothing

   ''' <summary>
   ''' Gets the Bitmap object.
   ''' </summary>
   ''' <value>The BMP.</value>
   Public ReadOnly Property bmp As Bitmap
       Get
           Return Me._bmp
       End Get
   End Property

   ''' <summary>
   ''' Gets the total amount of pixels that contains the Bitmap.
   ''' </summary>
   ''' <value>The pixel count.</value>
   Public ReadOnly Property PixelCount As Integer
       Get
           Return Me._PixelCount
       End Get
   End Property

#End Region

#Region " Classes "

   ''' <summary>
   ''' Stores specific pixel information of an image.
   ''' </summary>
   Public Class PixelData

       ''' <summary>
       ''' Gets or sets the pixel index.
       ''' </summary>
       ''' <value>The pixel index.</value>
       Public Property Index As Integer

       ''' <summary>
       ''' Gets or sets the pixel color.
       ''' </summary>
       ''' <value>The pixel color.</value>
       Public Property Color As Color

       ''' <summary>
       ''' Gets or sets the pixel coordinates relative to the image.
       ''' </summary>
       ''' <value>The pixel coordinates.</value>
       Public Property Coordinates As Point

   End Class

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="PixelUtil"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="PixelUtil"/> class.
   ''' </summary>
   ''' <param name="bmp">Indicates the Bitmap image to process it's pixels.</param>
   ''' <exception cref="System.Exception">PixelFormat unsupported.</exception>
   Public Sub New(ByVal bmp As Bitmap)

       If Not bmp.PixelFormat = PixelFormat.Format24bppRgb Then
           Throw New Exception("PixelFormat unsupported.")
       End If

       Me._bmp = bmp
       Me._PixelCount = Me.[Count]

   End Sub

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Returns a <c>'PixelData'</c> object containing information about each pixel in the image.
   ''' </summary>
   ''' <returns>List(Of PixelData).</returns>
   Public Function GetPixelData() As List(Of PixelData)

       If Me._PixelData Is Nothing Then

           Me._PixelData = New List(Of PixelData)

           ' Lock the Bitmap bits.
           Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
           Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)

           ' Get the address of the first line.
           Dim Pointer As IntPtr = bmpData.Scan0

           ' Hold the bytes of the bitmap into a Byte-Array.
           ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
           Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
           Dim rgbData(bmpBytes - 1) As Byte

           ' Copy the RGB values into the array.
           Marshal.Copy(Pointer, rgbData, 0, bmpBytes)

           ' Unlock the Bitmap bits.
           Me._bmp.UnlockBits(bmpData)

           ' Loop through each 24bpp-RGB value.
           For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3

               ' Set the pixel Data.
               Dim Pixel As New PixelData

               With Pixel

                   .Index = rgbIndex \ 3I

                   .Color = Color.FromArgb(red:=rgbData(rgbIndex),
                                           green:=rgbData(rgbIndex - 1I),
                                           blue:=rgbData(rgbIndex - 2I))

                   .Coordinates = New Point(X:=(.Index Mod bmpRect.Width),
                                            Y:=(.Index - (.Index Mod bmpRect.Width)) \ bmpRect.Width)

               End With

               ' Add the PixelData into the list.
               Me._PixelData.Add(Pixel)

           Next rgbIndex

       End If

       Return Me._PixelData

   End Function

   ''' <summary>
   ''' Returns a <c>'PixelData'</c> object containing information about a range of pixels in the image.
   ''' </summary>
   ''' <returns>List(Of PixelData).</returns>
   ''' <exception cref="System.Exception">Pixel index is out of range</exception>
   Public Function GetPixelData(ByVal RangeMin As Integer,
                                ByVal RangeMax As Integer) As List(Of PixelData)

       If Not (Me._PixelCount >= RangeMin AndAlso Me._PixelCount <= RangeMax) Then
           Throw New Exception("Pixel index is out of range.")
           Return Nothing
       End If

       ' Return the Pixel range.
       Return (From Pixel As PixelData In Me.GetPixelData()
               Where (Pixel.Index >= RangeMin AndAlso Pixel.Index <= RangeMax)).ToList

   End Function

   ''' <summary>
   ''' Searchs for the specified pixel-color inside the image and returns all the matches.
   ''' </summary>
   ''' <param name="PixelColor">Indicates the color to find.</param>
   ''' <returns>List(Of PixelData).</returns>
   Public Function SearchColor(ByVal PixelColor As Color) As List(Of PixelData)

       Return (From Pixel As PixelData In Me.GetPixelData
               Where Pixel.Color = PixelColor).ToList

   End Function

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Counts the number of pixels that contains the image.
   ''' </summary>
   ''' <returns>The number of pixels.</returns>
   Private Function [Count]() As Integer

       ' Lock the Bitmap bits.
       Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
       Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)

       ' Get the address of the first line.
       Dim Pointer As IntPtr = bmpData.Scan0

       ' Hold the bytes of the bitmap into a Byte-Array.
       ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
       Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
       Dim rgbData(bmpBytes - 1) As Byte

       ' Copy the RGB values into the array.
       Marshal.Copy(Pointer, rgbData, 0, bmpBytes)

       ' Unlock the Bitmap bits.
       Me._bmp.UnlockBits(bmpData)

       Return rgbData.Count

   End Function

#End Region

#Region " Hidden Methods "

   ''' <summary>
   ''' Serves as a hash function for a particular type.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub GetHashCode()
   End Sub

   ''' <summary>
   ''' Determines whether the specified System.Object is equal to the current System.Object.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub Equals()
   End Sub

   ''' <summary>
   ''' Returns a String that represents the current object.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub ToString()
   End Sub

#End Region

End Class

#End Region









Eleкtro

Una helper-class para administrar el contenido del archivo HOSTS de Windows:

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-11-2014
' ***********************************************************************
' <copyright file="HostsFile.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Public Class HostsFileTestClass
'
'    Private Sub HostsFileTestHandler() Handles MyBase.Shown
'
'        ' Instance the HostsFile Class.
'        Dim Hosts As New HostsFile()
'
'        ' Set a new mapping.
'        Dim Mapping As New HostsFile.MappingInfo
'        With Mapping
'            .HostName = "cuantodanio.es"
'            .IP = Hosts.LOCALHOST ' "127.0.0.1"
'            .Comment = "Test mapping comment."
'        End With
'
'        With Hosts
'
'            ' Delete the Host file.
'            If .FileExists Then
'                .FileDelete()
'            End If
'
'            ' Create a new one Hosts file.
'            .FileCreate()
'
'            ' Add some new mappings.
'            .Add(Mapping)
'            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
'
'            ' Check whether a mapping exists.
'            If .IsMapped(Mapping) Then
'                ' Disable the mapping.
'                .Disable(Mapping)
'            End If
'
'            ' Check whether an existing mapping is disabled.
'            If .IsDisabled("www.youtube.com") Then
'                ' Remove the mapping.
'                .Remove("www.youtube.com")
'            End If
'
'            ' Open the HOSTS file with the specified text-editor.
'            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
'
'        End With
'
'        ' Get the IP of a mapped Hostname.
'        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
'
'        ' Get all the hostname mappings
'        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
'        For Each MappingInfo As HostsFile.MappingInfo In Mappings
'
'            Dim sb As New System.Text.StringBuilder
'            With sb
'                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
'                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
'                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
'                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
'            End With
'
'            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
'
'        Next MappingInfo
'
'        ' Get all the hostname mappings that matches an ip address
'        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
'
'    End Sub
'
'End Class

#End Region

#Region " Imports "

Imports System.IO
Imports System.Net
Imports System.Text

#End Region

#Region " Hosts File "

''' <summary>
''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
''' </summary>
Public Class HostsFile

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="HostsFile"/> class.
    ''' </summary>
    ''' <param name="HOSTSLocation">
    ''' Optionaly indicates a custom Hosts file location.
    ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
    ''' </param>
    Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)

        If Not String.IsNullOrEmpty(HOSTSLocation) Then
            Me._HOSTSLocation = HOSTSLocation
        End If

    End Sub

    ''' <summary>
    ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

#End Region

#Region " Properties "

    ''' <summary>
    ''' The Hosts file location.
    ''' </summary>
    ''' <value>The Hosts file location.</value>
    Public ReadOnly Property HOSTSLocation As String
        Get
            Return _HOSTSLocation
        End Get
    End Property
    Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
    Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")

    ''' <summary>
    ''' The Hosts file encoding.
    ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
    ''' otherwise the entries will be ignored by Windows.
    ''' </summary>
    ''' <value>The Hosts file encoding.</value>
    Public Property HOSTSEncoding As Encoding
        Get
            Return _HOSTSEncoding
        End Get
        Set(ByVal value As Encoding)
            Me._HOSTSEncoding = value
        End Set
    End Property
    Private _HOSTSEncoding As Encoding = Encoding.Default

    ''' <summary>
    ''' Gets or sets the default 'LocalHost' IP address.
    ''' In most computers the default address is '127.0.0.1'.
    ''' </summary>
    ''' <value>The default LocalHost.</value>
    Public Property LOCALHOST As String
        Get
            Return Me._LOCALHOST
        End Get
        Set(ByVal value As String)
            Me._LOCALHOST = value
        End Set
    End Property
    Private _LOCALHOST As String = "127.0.0.1"

    ''' <summary>
    ''' Gets the default Hosts file header.
    ''' </summary>
    Private ReadOnly HostsHeader As String =
<a><![CDATA[
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
]]></a>.Value

#End Region

#Region " Types "

#Region " MappingInfo "

    ''' <summary>
    ''' Specifies info of a HOSTS file mapping.
    ''' </summary>
    Public Class MappingInfo

        ''' <summary>
        ''' Gets or sets the hostname.
        ''' </summary>
        ''' <value>The hostname.</value>
        Public Property HostName As String

        ''' <summary>
        ''' Gets or sets the IP address.
        ''' </summary>
        ''' <value>The IP address.</value>
        Public Property IP As String

        ''' <summary>
        ''' Gets or sets the mapping comment.
        ''' </summary>
        ''' <value>The mapping comment.</value>
        Public Property Comment As String

        ''' <summary>
        ''' This value is reserved.
        ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
        ''' </summary>
        ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
        Public Property IsDisabled As Boolean

    End Class

#End Region

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Adds a new mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <param name="IP">Indicates the IP address.</param>
    ''' <param name="Comment">Indicates a comment for this mapping.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
    ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
    Public Sub Add(ByVal HostName As String,
                   ByVal IP As String,
                   Optional ByVal Comment As String = Nothing)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

        ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
            Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))

        Else ' Add the entry.

            ' Fix value spacing.
            Dim EntryFormat As String =
                IP & HostName.Insert(0I, ControlChars.Tab) &
                If(Not String.IsNullOrEmpty(Comment),
                   Comment.Insert(0I, ControlChars.Tab & "#"c),
                   String.Empty)

            ' Write the mapping.
            File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Adds a new mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Add(ByVal MappingInfo As MappingInfo)

        Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)

    End Sub

    ''' <summary>
    ''' Disables an existing mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
    Public Sub Disable(ByVal HostName As String)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
            Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))

        Else ' Disable the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                        ' Disable the mapping.
                        Hosts(X) = Hosts(X).Insert(0I, "#"c)
                        Exit For

                    End If ' Host.Equals(...)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Disables an existing mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Disable(ByVal MappingInfo As MappingInfo)

        Me.Disable(MappingInfo.HostName)

    End Sub

    ''' <summary>
    ''' Removes a mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Sub Remove(ByVal HostName As String)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        Else ' Remove the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                        ' Remove the mapping.
                        Hosts.RemoveAt(X)
                        Exit For

                    End If ' Host.Equals(...)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Removes a mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Remove(ByVal MappingInfo As MappingInfo)

        Me.Remove(MappingInfo.HostName)

    End Sub

    ''' <summary>
    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    Public Function GetMappings() As List(Of MappingInfo)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Mappings As New List(Of MappingInfo)

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    Dim MappingInfo As New MappingInfo
                    With MappingInfo
                        .HostName = Parts(1I)
                        .IP = Parts(0I).Replace("#"c, String.Empty)
                        .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                        .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                    End With ' MappingInfo

                    Mappings.Add(MappingInfo)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return Mappings

        End If

    End Function

    ''' <summary>
    ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim MappingInfo As New MappingInfo

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then

                        With MappingInfo
                            .HostName = Parts(1I)
                            .IP = Parts(0I).Replace("#"c, String.Empty)
                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                        End With ' MappingInfo

                        Exit For

                    End If ' Parts(1I).Equals(Hostname)...

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return MappingInfo

        End If

    End Function

    ''' <summary>
    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
    ''' matching the specified IP address.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
    Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Mappings As New List(Of MappingInfo)

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then

                        Dim MappingInfo As New MappingInfo
                        With MappingInfo
                            .HostName = Parts(1I)
                            .IP = Parts(0I).Replace("#"c, String.Empty)
                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                        End With ' MappingInfo

                        Mappings.Add(MappingInfo)

                    End If

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return Mappings

        End If

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already mapped.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    Public Function IsMapped(ByVal HostName As String) As Boolean

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else
            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                        Return True
                    End If ' Host.Equals(HostName)...

                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

            Next X

            Return False

        End If ' Not Me.Exists()...

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already mapped.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
    Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean

        Return Me.IsMapped(MappingInfo.HostName)

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already disabled.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Function IsDisabled(ByVal HostName As String) As Boolean

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        Else
            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Result As Boolean = False

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                        Result = Hosts(X).TrimStart.StartsWith("#"c)
                        Exit For
                    End If ' Host.Equals(HostName)...

                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

            Next X

            Return Result

        End If

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already disabled.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
    Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean

        Return Me.IsDisabled(MappingInfo.HostName)

    End Function

    ''' <summary>
    ''' Checks whether the Hosts file exists.
    ''' </summary>
    ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
    Public Function FileExists() As Boolean

        Return File.Exists(Me._HOSTSLocation)

    End Function

    ''' <summary>
    ''' Creates the Hosts file.
    ''' </summary>
    Public Sub FileCreate()

        If Me.FileExists() Then
            File.Delete(Me._HOSTSLocation)
        End If

        File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)

    End Sub

    ''' <summary>
    ''' Deletes the Hosts file.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
    Public Sub FileDelete()

        If Not Me.FileExists() Then
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else
            File.Delete(Me._HOSTSLocation)

        End If

    End Sub

    ''' <summary>
    ''' Cleans the Hosts file.
    ''' This removes all the mappings and adds the default file header.
    ''' </summary>
    Public Sub FileClean()

        Me.FileCreate()

    End Sub

    ''' <summary>
    ''' Opens the Hosts file with the specified process.
    ''' </summary>
    ''' <param name="Process">
    ''' Indicates the process location.
    ''' Default value is: "notepad.exe".
    ''' </param>
    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
    ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
    Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")

        If Not Me.FileExists Then
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not File.Exists(Process) Then
            Throw New FileNotFoundException("Process not found.", Process)

        Else
            Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)

        End If

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Validates an IP address.
    ''' </summary>
    ''' <param name="Address">The IP address.</param>
    ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
    Private Function ValidateIP(ByVal Address As String) As Boolean

        Dim IP As IPAddress = Nothing
        Return IPAddress.TryParse(Address, IP)

    End Function

#End Region

End Class

#End Region








Eleкtro

#415
Una Class para cortar y unir archivos al mismo estilo que WinRAR (me refiero a la enumeración de los archivos partidos, este no comprime solo corta).

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-15-2014
' ***********************************************************************
' <copyright file="FileSplitter.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Imports "

Imports System.ComponentModel
Imports System.IO

#End Region

Public Class FileSplitter

#Region " Properties "

    ''' <summary>
    ''' Gets or sets the buffer-size to split or merge, in Bytes.
    ''' Default value is: 1048576 bytes (1 megabyte).
    ''' </summary>
    ''' <value>The buffer-size.</value>
    Public Property BufferSize As Integer = 1048576I

#End Region

#Region " Events "

#Region " EventHandlers "

    ''' <summary>
    ''' Occurs when the progress changes splitting a file.
    ''' </summary>
    Public Event SplitProgressChanged As EventHandler(Of SplitProgressChangedArgs)

    ''' <summary>
    ''' Occurs when the progress changes merging a file.
    ''' </summary>
    Public Event MergeProgressChanged As EventHandler(Of MergeProgressChangedArgs)

#End Region

#Region " Event Args "

#Region " SplitProgressChanged "

    ''' <summary>
    ''' Contains the Event arguments of the SplitProgressChanged Event.
    ''' </summary>
    Public Class SplitProgressChangedArgs : Inherits EventArgs

#Region " Constructors "

        ''' <summary>
        ''' Prevents a default instance of the <see cref="SplitProgressChangedArgs"/> class from being created.
        ''' </summary>
        Private Sub New()
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="SplitProgressChangedArgs"/> class.
        ''' </summary>
        ''' <param name="TotalProgress">The total progress value.</param>
        ''' <param name="ChunkProgress">The current chunk progress value.</param>
        ''' <param name="ChunksToCreate">The amount of chunks to create.</param>
        ''' <param name="ChunksCreated">The amount of created chunks.</param>
        Public Sub New(ByVal TotalProgress As Double,
                       ByVal ChunkProgress As Double,
                       ByVal ChunksToCreate As Integer,
                       ByVal ChunksCreated As Integer)

            Me._TotalProgress = TotalProgress
            Me._ChunkProgress = ChunkProgress
            Me._ChunksToCreate = ChunksToCreate
            Me._ChunksCreated = ChunksCreated

        End Sub

#End Region

#Region " Properties "

        ''' <summary>
        ''' Gets the total progress value.
        ''' (From 0 to 100)
        ''' </summary>
        ''' <value>The total progress value.</value>
        Public ReadOnly Property TotalProgress As Double
            Get
                Return Me._TotalProgress
            End Get
        End Property
        Private _TotalProgress As Double = 0.0R

        ''' <summary>
        ''' Gets the current chunk progress value.
        ''' </summary>
        ''' <value>The current chunk progress value.</value>
        Public ReadOnly Property ChunkProgress As Double
            Get
                Return Me._ChunkProgress
            End Get
        End Property
        Private _ChunkProgress As Double = 0.0R

        ''' <summary>
        ''' Gets the amount of chunks to create.
        ''' </summary>
        ''' <value>The amount of chunks to create.</value>
        Public ReadOnly Property ChunksToCreate As Integer
            Get
                Return Me._ChunksToCreate
            End Get
        End Property
        Private _ChunksToCreate As Integer = 0I

        ''' <summary>
        ''' Gets the amount of created chunks.
        ''' </summary>
        ''' <value>The amount of created chunks.</value>
        Public ReadOnly Property ChunksCreated As Integer
            Get
                Return Me._ChunksCreated
            End Get
        End Property
        Private _ChunksCreated As Integer = 0I

#End Region

#Region " Hidden Methods "

        ''' <summary>
        ''' Serves as a hash function for a particular type.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub GetHashCode()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are considered equal.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub Equals()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are the same instance.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Private Shadows Sub ReferenceEquals()
        End Sub

        ''' <summary>
        ''' Returns a String that represents the current object.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub ToString()
        End Sub

#End Region

    End Class

#End Region

#Region " MergeProgressChangedArgs "

    ''' <summary>
    ''' Contains the Event arguments of the MergeProgressChangedArgs Event.
    ''' </summary>
    Public Class MergeProgressChangedArgs : Inherits EventArgs

#Region " Constructors "

        ''' <summary>
        ''' Prevents a default instance of the <see cref="MergeProgressChangedArgs"/> class from being created.
        ''' </summary>
        Private Sub New()
        End Sub

        ''' <summary>
        ''' Initializes a new instance of the <see cref="MergeProgressChangedArgs"/> class.
        ''' </summary>
        ''' <param name="TotalProgress">The total progress value.</param>
        ''' <param name="ChunkProgress">The current chunk progress value.</param>
        ''' <param name="ChunksToMerge">The amount of chunks to merge.</param>
        ''' <param name="ChunksMerged">The amount of merged chunks.</param>
        Public Sub New(ByVal TotalProgress As Double,
                       ByVal ChunkProgress As Double,
                       ByVal ChunksToMerge As Integer,
                       ByVal ChunksMerged As Integer)

            Me._TotalProgress = TotalProgress
            Me._ChunkProgress = ChunkProgress
            Me._ChunksToMerge = ChunksToMerge
            Me._ChunksMerged = ChunksMerged

        End Sub

#End Region

#Region " Properties "

        ''' <summary>
        ''' Gets the total progress value.
        ''' (From 0 to 100)
        ''' </summary>
        ''' <value>The total progress value.</value>
        Public ReadOnly Property TotalProgress As Double
            Get
                Return Me._TotalProgress
            End Get
        End Property
        Private _TotalProgress As Double = 0.0R

        ''' <summary>
        ''' Gets the current chunk progress value.
        ''' </summary>
        ''' <value>The current chunk progress value.</value>
        Public ReadOnly Property ChunkProgress As Double
            Get
                Return Me._ChunkProgress
            End Get
        End Property
        Private _ChunkProgress As Double = 0.0R

        ''' <summary>
        ''' Gets the amount of chunks to merge.
        ''' </summary>
        ''' <value>The amount of chunks to merge.</value>
        Public ReadOnly Property ChunksToMerge As Integer
            Get
                Return Me._ChunksToMerge
            End Get
        End Property
        Private _ChunksToMerge As Integer = 0I

        ''' <summary>
        ''' Gets the amount of merged chunks.
        ''' </summary>
        ''' <value>The amount of merged chunks.</value>
        Public ReadOnly Property ChunksMerged As Integer
            Get
                Return Me._ChunksMerged
            End Get
        End Property
        Private _ChunksMerged As Integer = 0I

#End Region

#Region " Hidden Methods "

        ''' <summary>
        ''' Serves as a hash function for a particular type.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub GetHashCode()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are considered equal.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub Equals()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are the same instance.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Private Shadows Sub ReferenceEquals()
        End Sub

        ''' <summary>
        ''' Returns a String that represents the current object.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub ToString()
        End Sub

#End Region

    End Class

#End Region

#End Region

#End Region

#Region " Hidden Methods "

    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetHashCode()
    End Sub

    ''' <summary>
    ''' Determines whether the specified System.Object instances are considered equal.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    ''' <summary>
    ''' Determines whether the specified System.Object instances are the same instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Private Shadows Sub ReferenceEquals()
    End Sub

    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ToString()
    End Sub

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Splits the specified file.
    ''' </summary>
    ''' <param name="InputFile">Indicates the file to split.</param>
    ''' <param name="ChunkSize">Indicates the size of each chunk.</param>
    ''' <param name="ChunkName">Indicates the name-format for the chunks.</param>
    ''' <param name="ChunkExt">Indicates the file-extension for the chunks.</param>
    ''' <param name="Overwrite">
    ''' If set to <c>true</c> any existing file will be overwritten if needed to create a chunk,
    ''' otherwise, an exception will be thrown.
    ''' </param>
    ''' <param name="DeleteAfterSplit">If set to <c>true</c> the input file will be deleted after a successful split.</param>
    ''' <exception cref="System.IO.FileNotFoundException">The specified file doesn't exists.</exception>
    ''' <exception cref="System.IO.IOException">File already exists.</exception>
    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
    Public Sub Split(ByVal InputFile As String,
                     ByVal ChunkSize As Long,
                     Optional ByVal ChunkName As String = Nothing,
                     Optional ByVal ChunkExt As String = Nothing,
                     Optional ByVal Overwrite As Boolean = False,
                     Optional ByVal DeleteAfterSplit As Boolean = False)

        If Not File.Exists(InputFile) Then
            Throw New FileNotFoundException("The specified file doesn't exists.", InputFile)
            Exit Sub
        End If

        ' The progress event arguments.
        Dim ProgressArguments As SplitProgressChangedArgs

        ' FileInfo instance of the input file.
        Dim fInfo As New FileInfo(InputFile)

        ' The total filesize to split, in bytes.
        Dim TotalSize As Long = fInfo.Length

        ' The remaining size to calculate the percentage, in bytes.
        Dim SizeRemaining As Long = TotalSize

        ' Counts the length of the current chunk file to calculate the percentage, in bytes.
        Dim SizeWritten As Long = 0L

        ' The buffer to read data and write the chunks.
        Dim Buffer As Byte() = New Byte() {}

        ' The buffer length.
        Dim BufferLength As Integer = Me.BufferSize

        ' The total amount of chunks to create.
        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))

        ' Keeps track of the current chunk.
        Dim ChunkIndex As Integer = 0I

        ' Keeps track of the total percentage done.
        Dim TotalProgress As Double = 0.0R

        ' Keeps track of the current chunk percentage done.
        Dim ChunkProgress As Double = 0.0R

        ' A zero-filled string to enumerate the chunk files.
        Dim Zeros As String = String.Empty

        ' The given filename for each chunk.
        Dim ChunkFile As String = String.Empty

        ' The chunk file basename.
        ChunkName = If(String.IsNullOrEmpty(ChunkName),
                       Path.Combine(fInfo.DirectoryName, Path.GetFileNameWithoutExtension(fInfo.Name)),
                       Path.Combine(fInfo.DirectoryName, ChunkName))

        ' The chunk file extension.
        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
                      fInfo.Extension.Substring(1I),
                      ChunkExt)

        ' If ChunkSize is bigger than filesize then...
        If ChunkSize >= fInfo.Length Then
            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
            Exit Sub

            ' For cases where a chunksize is smaller than the buffersize.
        ElseIf ChunkSize < BufferLength Then
            BufferLength = CInt(ChunkSize)

        End If ' ChunkSize <>...

        ' If not file-overwrite is allowed then...
        If Not Overwrite Then

            For Index As Integer = 0I To (ChunkCount)

                ' Set chunk filename.
                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)

                ' If chunk file already exists then...
                If File.Exists(ChunkFile) Then

                    Throw New IOException(String.Format("File already exists: {0}", ChunkFile))
                    Exit Sub

                End If ' File.Exists(ChunkFile)

            Next Index

            Zeros = String.Empty
            ChunkFile = String.Empty

        End If ' Overwrite

        ' Open the file to start reading bytes.
        Using InputStream As New FileStream(fInfo.FullName, FileMode.Open)

            Using BinaryReader As New BinaryReader(InputStream)

                While (InputStream.Position < InputStream.Length)

                    ' Set chunk filename.
                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)

                    ' Reset written byte-length counter.
                    SizeWritten = 0L


                    ' Create the chunk file to Write the bytes.
                    Using OutputStream As New FileStream(ChunkFile, FileMode.Create)

                        Using BinaryWriter As New BinaryWriter(OutputStream)

                            ' Read until reached the end-bytes of the input file.
                            While (SizeWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                                ' Read bytes from the original file (BufferSize byte-length).
                                Buffer = BinaryReader.ReadBytes(BufferLength)

                                ' Write those bytes in the chunk file.
                                BinaryWriter.Write(Buffer)

                                ' Increment the bytes-written counter.
                                SizeWritten += Buffer.Count

                                ' Decrease the bytes-remaining counter.
                                SizeRemaining -= Buffer.Count

                                ' Set the total progress.
                                TotalProgress = (TotalSize - SizeRemaining) * (100I / TotalSize)

                                ' Set the current chunk progress.
                                ChunkProgress =
                                    If(Not ChunkIndex = ChunkCount,
                                       (100I / ChunkSize) * (SizeWritten - BufferLength),
                                       (100I / (InputStream.Length - (ChunkSize * ChunkIndex))) * (SizeWritten - BufferLength))

                                ' Set the progress event-arguments.
                                ProgressArguments =
                                    New SplitProgressChangedArgs(
                                        TotalProgress:=If(Not TotalProgress > 99.9R, TotalProgress, 99.9R),
                                        ChunkProgress:=ChunkProgress,
                                        ChunksToCreate:=ChunkCount + 1I,
                                        ChunksCreated:=ChunkIndex)

                                ' Report the progress event-arguments.
                                RaiseEvent SplitProgressChanged(Me, ProgressArguments)

                            End While ' (SizeWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                            OutputStream.Flush()

                        End Using ' BinaryWriter

                    End Using ' OutputStream

                    ChunkIndex += 1I 'Increment the chunk file counter.

                End While ' InputStream.Position < InputStream.Length

            End Using ' BinaryReader

        End Using ' InputStream

        ' Set the progress event-arguments.
        ProgressArguments =
            New SplitProgressChangedArgs(
                TotalProgress:=100.0R,
                ChunkProgress:=100.0R,
                ChunksToCreate:=ChunkCount + 1I,
                ChunksCreated:=ChunkIndex)

        ' Report the progress event-arguments.
        RaiseEvent SplitProgressChanged(Me, ProgressArguments)

    End Sub

    ''' <summary>
    ''' Merges the specified file.
    ''' </summary>
    ''' <param name="InputFile">
    ''' Indicates the file to merge its chunks.
    ''' This should be the first chunk file (eg: 'File.Part.01.mkv')
    ''' </param>
    ''' <param name="OutputFile">Indicates the output file.</param>
    ''' <param name="Overwrite">
    ''' If set to <c>true</c>, in case that the 'OutputFile' exists it will be overwritten,
    ''' otherwise, an exception will be thrown.
    ''' </param>
    ''' <param name="DeleteChunksAfterMerged">
    ''' If set to <c>true</c>, the chunks will be deleted after a successful.
    ''' </param>
    ''' <exception cref="System.IO.FileNotFoundException">The specified file doesn't exists.</exception>
    ''' <exception cref="System.IO.IOException">File already exists.</exception>
    ''' <exception cref="System.Exception">The last chunk file is missing.</exception>
    ''' <exception cref="System.Exception">Unexpected chunk filesize-count detected.</exception>
    Public Sub Merge(ByVal InputFile As String,
                     Optional ByVal OutputFile As String = Nothing,
                     Optional ByVal Overwrite As Boolean = False,
                     Optional DeleteChunksAfterMerged As Boolean = False)

        If Not File.Exists(InputFile) Then
            Throw New FileNotFoundException("The specified file doesn't exists.", InputFile)
            Exit Sub

        ElseIf Not Overwrite AndAlso File.Exists(OutputFile) Then
            Throw New IOException(String.Format("File already exists: {0}", OutputFile))
            Exit Sub

        End If

        ' The progress event arguments.
        Dim ProgressArguments As MergeProgressChangedArgs

        ' FileInfo instance of the input chunk file.
        Dim fInfo As New FileInfo(InputFile)

        ' Get the filename without extension.
        Dim Filename As String = Path.GetFileNameWithoutExtension(fInfo.FullName)
        ' Remove the chunk enumeration from the filename.
        Filename = Filename.Substring(0I, Filename.LastIndexOf("."c))

        ' TSet the pattern to find the chunk files to merge.
        Dim ChunkPatternSearch As String =
            Filename & ".*" & If(Not String.IsNullOrEmpty(fInfo.Extension), fInfo.Extension, "")

        ' Retrieve all the chunk files to merge them.
        Dim Chunks As IEnumerable(Of FileInfo) =
           From Chunk As String In
           Directory.GetFiles(fInfo.DirectoryName, ChunkPatternSearch, SearchOption.TopDirectoryOnly)
           Select New FileInfo(Chunk)

        If Chunks.Count < 2I Then ' If chunk files are less than 2 then...
            Throw New Exception("The last chunk file is missing.")
            Exit Sub
        End If

        ' The total filesize to merge, in bytes.
        Dim TotalSize As Long =
            (From Chunk As FileInfo In Chunks Select Chunk.Length).Sum

        ' Gets the filesize of the chunk files and the last chunk file, in bytes.
        Dim ChunkSizes As Long() =
            (From Chunk As FileInfo In Chunks
             Select Chunk.Length Order By Length Descending
            ).Distinct.ToArray

        If ChunkSizes.Count > 2I Then ' If chunk sizes are more than 2...
            Throw New Exception("Unexpected chunk filesize-count detected.")
            Exit Sub
        End If

        ' The remaining size to calculate the percentage, in bytes.
        Dim SizeRemaining As Long = TotalSize

        ' Counts the length of the current chunk file to calculate the percentage, in bytes.
        Dim SizeWritten As Long = 0L

        ' Counts the length of the written size on the current chunk file, in bytes.
        Dim ChunkSizeWritten As Long = 0L

        ' The buffer to read data and merge the chunks.
        Dim Buffer As Byte() = New Byte() {}

        ' The buffer length.
        Dim BufferLength As Integer = Me.BufferSize

        ' The total amount of chunks to merge.
        Dim ChunkCount As Integer = Chunks.Count

        ' Keeps track of the current chunk.
        Dim ChunkIndex As Integer = 0I

        ' Keeps track of the total percentage done.
        Dim TotalProgress As Double = 0.0R

        ' Create the output file to merge the chunks inside.
        Using OutputStream As New FileStream(OutputFile, FileMode.Create)

            Using BinaryWriter As New BinaryWriter(OutputStream)

                ' Iterate the chunks.
                For Each Chunk As FileInfo In Chunks

                    ' Open the chunk to start reading bytes.
                    Using InputStream As New FileStream(Chunk.FullName, FileMode.Open)

                        Using BinaryReader As New BinaryReader(InputStream)

                            ' Read until reached the end-bytes of the chunk file.
                            While (InputStream.Position < InputStream.Length)

                                ' Read bytes from the chunk file (BufferSize byte-length).
                                Buffer = BinaryReader.ReadBytes(BufferLength)

                                ' Write those bytes in the output file.
                                BinaryWriter.Write(Buffer)

                                ' Increment the bytes-written counters.
                                SizeWritten += Buffer.Count
                                ChunkSizeWritten += Buffer.Count

                                ' Decrease the bytes-remaining counter.
                                SizeRemaining -= Buffer.Count

                                ' Set the total progress.
                                TotalProgress = (TotalSize - SizeRemaining) * (100I / TotalSize)

                                ' Set the progress event-arguments.
                                ProgressArguments = New MergeProgressChangedArgs(
                                    TotalProgress:=If(Not TotalProgress > 99.9R, TotalProgress, 99.9R),
                                    ChunkProgress:=(100I / InputStream.Length) * (ChunkSizeWritten - BufferLength),
                                    ChunksToMerge:=ChunkCount,
                                    ChunksMerged:=ChunkIndex)

                                ' Report the progress.
                                RaiseEvent MergeProgressChanged(Me, ProgressArguments)

                            End While ' (InputStream.Position < InputStream.Length)

                            ChunkIndex += 1I ' Increment the chunk file counter.
                            ChunkSizeWritten = 0L ' Reset the bytes-written for the next chunk.

                        End Using ' BinaryReader

                    End Using ' InputStream

                Next Chunk

                OutputStream.Flush()

            End Using ' BinaryWriter

        End Using ' OutputStream

        ' Set the progress event-arguments.
        ProgressArguments = New MergeProgressChangedArgs(
            TotalProgress:=100.0R,
            ChunkProgress:=100.0R,
            ChunksToMerge:=ChunkCount,
            ChunksMerged:=ChunkIndex)

        ' Report the progress.
        RaiseEvent MergeProgressChanged(Me, ProgressArguments)

        If DeleteChunksAfterMerged Then ' Delethe the chunk files.

            For Each Chunk As FileInfo In Chunks
                File.Delete(Chunk.FullName)
            Next Chunk

        End If ' DeleteChunksAfterMerged

    End Sub

#End Region

End Class



Ejemplo de uso:



Código (vbnet) [Seleccionar]
Public Class FileSplitter_Test

   ' Some Sizes to choose.
   Private ReadOnly Megabyte As Integer = 1048576I
   Private ReadOnly Gigabyte As Integer = 1073741824I

   ' The controls that will report the progress.
   Private LabelSplit1, LabelSplit2, LabelSplit3 As New Label
   Private LabelMerge1, LabelMerge2, LabelMerge3 As New Label

   ' The controls to split or merge.
   Private WithEvents ButtonSplit, ButtonMerge As New Button

   ' The FileSplitter instance.
   Private WithEvents Splitter As New FileSplitter() With
       {
         .BufferSize = (Megabyte * 10I)
       } ' With BufferSize of 10 Megabytes.

   Public Sub New()

       ' This call is required by the designer.
       InitializeComponent()

       ' Set the Form properties.
       With Me
           .Size = New Point(400, 200)
           .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
           .MaximizeBox = False
       End With

       ' Set the control properties.
       With ButtonSplit
           .Text = "Split"
           .Font = New Font(Me.Font.FontFamily, 14.0F, FontStyle.Bold)
           .Size = New Point(200I, 75I)
           .Location = New Point(0I, 0I)
           .Cursor = Cursors.Hand
       End With

       With ButtonMerge
           .Text = "Merge"
           .Font = New Font(Me.Font.FontFamily, 14.0F, FontStyle.Bold)
           .Size = New Point(200I, 75I)
           .Location = New Point(ButtonSplit.Location.X + ButtonSplit.Width, 0I)
           .Cursor = Cursors.Hand
       End With

       With LabelSplit1
           .Text = "Total Progress:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(0I, ButtonSplit.Location.Y + ButtonSplit.Height + 10I)
       End With

       With LabelSplit2
           .Text = "Chunk Progress:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(0I, LabelSplit1.Location.Y + LabelSplit1.Height)
       End With

       With LabelSplit3
           .Text = "Chunk Count:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(0I, LabelSplit2.Location.Y + LabelSplit2.Height)
       End With

       With LabelMerge1
           .Text = "Total Progress:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(ButtonMerge.Location.X, ButtonMerge.Location.Y + ButtonMerge.Height + 10I)
       End With

       With LabelMerge2
           .Text = "Chunk Progress:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(ButtonMerge.Location.X, LabelMerge1.Location.Y + LabelMerge1.Height)
       End With

       With LabelMerge3
           .Text = "Chunk Count:"
           .AutoSize = True
           .Font = New Font(Me.Font.FontFamily, 9.0F, FontStyle.Regular)
           .Location = New Point(ButtonMerge.Location.X, LabelMerge2.Location.Y + LabelMerge2.Height)
       End With

       ' Add the controls into the form.
       Me.Controls.AddRange({LabelSplit1, LabelSplit2, LabelSplit3})
       Me.Controls.AddRange({LabelMerge1, LabelMerge2, LabelMerge3})
       Me.Controls.AddRange({ButtonSplit, ButtonMerge})

   End Sub

   ''' <summary>
   ''' Handles the 'Click' event of the 'ButtonSplit' control.
   ''' </summary>
   Private Sub ButtonSplit_Click() Handles ButtonSplit.Click

       Splitter.Split(InputFile:="C:\File.mkv",
                      ChunkSize:=Gigabyte,
                      ChunkName:="File.Part",
                      ChunkExt:="fs",
                      Overwrite:=True,
                      DeleteAfterSplit:=False)

   End Sub

   ''' <summary>
   ''' Handles the 'Click' event of the 'ButtonMerge' control.
   ''' </summary>
   Private Sub ButtonMerge_Click() Handles ButtonMerge.Click

       Splitter.Merge(InputFile:="C:\File.Part.1.fs",
                      OutputFile:="C:\Merged.mkv",
                      Overwrite:=True,
                      DeleteChunksAfterMerged:=True)

   End Sub

   ''' <summary>
   ''' Handles the 'SplitProgressChangedArgs' event of the 'Splitter' object.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="FileSplitter.SplitProgressChangedArgs"/> instance containing the event data.</param>
   Private Sub Splitter_SplitProgressChangedArgs(ByVal sender As Object, ByVal e As FileSplitter.SplitProgressChangedArgs) _
   Handles Splitter.SplitProgressChanged

       LabelSplit1.Text = String.Format("Total Progress: {0}%", e.TotalProgress.ToString("n1"))
       LabelSplit2.Text = String.Format("Chunk Progress: {0}%", e.ChunkProgress.ToString("n1"))
       LabelSplit3.Text = String.Format("Chunk Count: {0} of {1}", CStr(e.ChunksCreated), CStr(e.ChunksToCreate))
       Application.DoEvents()

   End Sub

   ''' <summary>
   ''' Handles the 'MergeProgressChangedArgs' event of the 'Splitter' object.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="FileSplitter.MergeProgressChangedArgs"/> instance containing the event data.</param>
   Private Sub Splitter_MergeProgressChangedArgs(ByVal sender As Object, ByVal e As FileSplitter.MergeProgressChangedArgs) _
   Handles Splitter.MergeProgressChanged

       LabelMerge1.Text = String.Format("Total Progress: {0}%", e.TotalProgress.ToString("n1"))
       LabelMerge2.Text = String.Format("Chunk Progress: {0}%", e.ChunkProgress.ToString("n1"))
       LabelMerge3.Text = String.Format("Chunk Count: {0} of {1}", CStr(e.ChunksMerged), CStr(e.ChunksToMerge))
       Application.DoEvents()

   End Sub

End Class








Eleкtro

#416
Aquí explico una manera de limitar manualmente la aplicación a única instancia (Single-Instance), mediante el MUTEX.



Código (vbnet) [Seleccionar]
' Single-Instance Application Example
' By Elektro

' Instructions:
' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
' 2. Copy and paste this code to replace the 'MyApplication' class contents.
' 3. Define a proper identifier for 'MutexID' property.

Namespace My

   Partial Friend Class MyApplication

#Region " Properties "

       ''' <summary>
       ''' Gets the current process mutex identifier.
       ''' </summary>
       ''' <value>the current process mutex identifier.</value>
       ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
       Private ReadOnly Property MutexID As String
           Get
               ' Define a Golabl Unique Identifier to name the Mutex.
               Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"

               If Guid.TryParse(input:=Id, result:=New Guid) Then
                   Return Id
               Else
                   Throw New FormatException("The specified value is not in a valid GUID format.")
               End If

           End Get
       End Property

#End Region

#Region " Private Methods "

       ''' <summary>
       ''' Determines whether this is the unique instance that is running for this process.
       ''' </summary>
       ''' <returns><c>true</c> if this is the unique instance; otherwise, <c>false</c>.</returns>
       Private Function IsUniqueInstance() As Boolean

           Dim mtx As Threading.Mutex = Nothing

           Try
               mtx = Threading.Mutex.OpenExisting(name:=Me.MutexID)
               mtx.Close()
               mtx = Nothing
           Catch
               mtx = New Threading.Mutex(initiallyOwned:=True, name:=Me.MutexID)
           End Try

           Return mtx IsNot Nothing

       End Function

#End Region

#Region " Event-Handlers "

       ''' <summary>
       ''' This occurs when the application starts, before the startup Form is created.
       ''' </summary>
       ''' <param name="sender">The source of the event.</param>
       ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
       Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
       Handles Me.Startup

           ' If there is more than one instance running of this process with the same mutex then...
           If Not Me.IsUniqueInstance Then ' Prevent multi-instancing.

               MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
                              Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)

               ' Cancel the application execution.
               e.Cancel = True

           End If

       End Sub

#End Region

   End Class ' MyApplication

End Namespace








Eleкtro

#417
Un ejemplo de como añadir y usar un control WPF (no un proyecto) en Winforms, en tiempo de ejecución.

En este ejemplo uso un control simple que imita el indicador de progreso de Windows 8:



Código (vbnet) [Seleccionar]
' Example of how to add an WPF Control in a WinForms project at execution time.
' By Elektro

' Instructions:
' 1. Compile your own WPF user-control or download this one: http://www.codeproject.com/Articles/700185/Windows-Progress-Ring?msg=4884207#xx4884207xx
' 2. Add a reference to 'WindowsformsIntegration', 'PresentationFramework', 'PresentationCore', 'WindowsBase' and 'System.Xaml'.
' 3. Add a reference to our WPF library, in this example is: 'WindowsProgressRing.dll'
' 4. If the 'WindowsProgressRing.dll' user-control doesnt's load properly, set the targeting Framework to '4.5'.

#Region " Imports "

Imports System.Windows.Forms.Integration ' ElementHost

#End Region

#Region " WPFControl_TestClass "

Public Class WPFControl_TestClass

   ''' <summary>
   ''' The ElementHost instance that will host the WPF user-control.
   ''' </summary>
   Dim WPFHost As New ElementHost With {.Dock = DockStyle.Fill}

   ''' <summary>
   ''' The WPF user-control instance.
   ''' </summary>
   Dim WPFControl As New NMT.Wpf.Controls.WindowsProgressRing

   ''' <summary>
   ''' Initializes a new instance of the <see cref="WPFControl_TestClass"/> class.
   ''' </summary>
   Public Sub New()

       ' This call is required by the designer.
       InitializeComponent()

       With Me ' Set the Form properties.
           .StartPosition = FormStartPosition.CenterScreen
           .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
           .MaximizeBox = False
           .ShowIcon = False
           .BackColor = Color.Black
           .Size = New Drawing.Size(320I, 320I)

           .Controls.Add(WPFHost) ' Add the ElementHost.
       End With ' Me

       With WPFHost ' Set the ElementHost properties.
           .Width = 120I
           .Height = 120I
           WPFHost.Child = WPFControl ' Add the WPF Control.
       End With ' WPFHost

       With WPFControl ' Set the WPF Control properties.
           .Items = 60I
           .Width = 120.0R
           .Height = 120.0R
           .Speed = New Windows.Duration(TimeSpan.FromSeconds(2.5R))
           .Background = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B))
           .Foreground = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.DodgerBlue.R, Color.DodgerBlue.G, Color.DodgerBlue.B))
       End With ' WPFControl

   End Sub

End Class ' WPFControl_TestClass

#End Region








Eleкtro

#418
Este código es parecido al ejemplo que mostré de como implementar una prevención de múltiples instancias, pero la diferencia de este código es que se puede especificar un máximo de instancias múltiples (en la propiedad 'SemaphID')



Código (vbnet) [Seleccionar]
' Multi-Instance Limit Example
' By Elektro

' Instructions:
' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
' 2. Copy and paste this code to replace the 'MyApplication' class contents.
' 3. Define a proper identifier for 'SemaphID' property.

Namespace My

   Partial Friend Class MyApplication

       ''' <summary>
       ''' The semaphore object used to limit the number of instances.
       ''' </summary>
       Private Semaph As Threading.Semaphore = Nothing

       ''' <summary>
       ''' Gets the current semaphore object identifier.
       ''' </summary>
       ''' <value>The current process semaphore identifier.</value>
       ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
       Private ReadOnly Property SemaphID As String
           Get

               ' Define a Golabl Unique Identifier to name the semaphore object.
               Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"

               If Guid.TryParse(input:=Id, result:=New Guid) Then
                   Return Id
               Else
                   Throw New FormatException("The specified value is not in a valid GUID format.")
               End If

           End Get
       End Property

       ''' <summary>
       ''' Gets the maximum instances allowed for this process.
       ''' </summary>
       ''' <value>The maximum instances allowed for this process.</value>
       Private ReadOnly Property MaxInstances As Integer
           Get
               Return 3
           End Get
       End Property

       ''' <summary>
       ''' Determines whether the semaphore can receive a signal.
       ''' </summary>
       ''' <returns><c>true</c> if this instance [can set semaphore]; otherwise, <c>false</c>.</returns>
       Private Function CanSetSemaphore() As Boolean

           Semaph = New Threading.Semaphore(initialCount:=Me.MaxInstances,
                                            maximumCount:=Me.MaxInstances,
                                            name:=Me.SemaphID)

           Return Semaph.WaitOne(100I)

       End Function

       ''' <summary>
       ''' This occurs when the application starts, before the startup Form is created.
       ''' </summary>
       ''' <param name="sender">The source of the event.</param>
       ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
       Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
       Handles Me.Startup

           ' If there is more than the maximum allowed instances running with the same id then...
           If Not Me.CanSetSemaphore Then ' Prevent multi-instancing.

               MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
                              Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)

               ' Cancel the application Startup to terminate the process.
               e.Cancel = True

           End If

       End Sub

       ''' <summary>
       ''' This occurs when the application shuts down.
       ''' </summary>
       ''' <param name="sender">The source of the event.</param>
       ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
       Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As EventArgs) _
       Handles Me.Shutdown

           If Semaph IsNot Nothing Then

               ' Free the semaphore to allow next app runs.
               Semaph.Release()
               Semaph.Close()
               Semaph = Nothing

           End If ' semaph IsNot Nothing

       End Sub

   End Class ' MyApplication

End Namespace








Eleкtro

Convierte un String a HTMLDocument

Código (vbnet) [Seleccionar]
   ' String To HtmlDocument
   ' By Elektro
   '
   ' Example Usage:
   ' Dim Document As HtmlDocument = StringToHtmlDocument(IO.File.ReadAllText("C:\File.html", Text.Encoding.Default))
   '
   ''' <summary>
   ''' Converts a <see cref="String"/> to an <see cref="HTMLDocument"/>.
   ''' </summary>
   ''' <param name="str">Indicates the string.</param>
   ''' <returns>The <see cref="HTMLDocument"/> object.</returns>
   Public Function StringToHtmlDocument(ByVal str As String) As HtmlDocument

       Using wb As New WebBrowser

           wb.ScriptErrorsSuppressed = True
           wb.DocumentText = ""
           wb.Document.OpenNew(replaceInHistory:=True)
           wb.Document.Write(str)
           Return wb.Document

       End Using

   End Function





Obtiene los XPaths de un XMLDocument:



Código (vbnet) [Seleccionar]
   ' Get XPaths
   ' By Elektro
   '
   ' Example Usage:
   '
   ' Dim xDoc As New Xml.XmlDocument
   ' xDoc.Load("C:\File.xml")
   ' Dim XPathList As List(Of String) = GetXPaths(xDoc)
   ' ListBox1.Items.AddRange((From XPath As String In XPathList Select XPath).ToArray)

   ''' <summary>
   ''' Gets all the XPath expressions of an XML Document.
   ''' </summary>
   ''' <param name="Document">Indicates the XML document.</param>
   ''' <returns>List(Of System.String).</returns>
   Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String)

       Dim XPathList As New List(Of String)

       Dim XPath As String = String.Empty

       For Each Child As Xml.XmlNode In Document.ChildNodes

           If Child.NodeType = Xml.XmlNodeType.Element Then
               GetXPaths(Child, XPathList, XPath)
           End If

       Next ' child

       Return XPathList

   End Function

   ''' <summary>
   ''' Gets all the XPath expressions of an XML Node.
   ''' </summary>
   ''' <param name="Node">Indicates the XML node.</param>
   ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
   ''' <param name="XPath">Indicates the current XPath.</param>
   Private Sub GetXPaths(ByVal Node As Xml.XmlNode,
                         ByRef XPathList As List(Of String),
                         Optional ByVal XPath As String = Nothing)

       XPath &= "/" & Node.Name

       If Not XPathList.Contains(XPath) Then
           XPathList.Add(XPath)
       End If

       For Each Child As Xml.XmlNode In Node.ChildNodes

           If Child.NodeType = Xml.XmlNodeType.Element Then
               GetXPaths(Child, XPathList, XPath)
           End If

       Next ' child

   End Sub