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

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

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

Validar la sintaxis de un RegEx

Código (vbnet) [Seleccionar]

   #Region " Validate RegEx "
   
      ' [ Validate RegEx Function ]
      '
      ' //By Elektro H@cker
      '
      ' Examples :
      ' MsgBox(Validate_RegEx("\"))  ' Result: False
      ' MsgBox(Validate_RegEx("\\")) ' Result: True  
   
   Private Function Validate_RegEx(Pattern As String) As Boolean

       Dim temp_RegEx As System.Text.RegularExpressions.Regex

       Try
           temp_RegEx = New System.Text.RegularExpressions.Regex(Pattern)
           Return True
       Catch
           Return False
       Finally
           temp_RegEx = Nothing
       End Try

   End Function
   
   #End Region








Eleкtro

 Resalta los colores de las coincidencias encontradas de una expresión regular en el contenido de un RichTextBox.

Código (vbnet) [Seleccionar]


   #Region " Highlight RegEx In RichTextBox "
   
      ' [ Highlight RegEx In RichTextBox Function ]
      '
      ' //By Elektro H@cker
      '
      ' Examples :
      '
      ' RichTextBox1.Text = String.Format("{0}{1}{0}{1}{0}{1}", "Hello World!", vbNewLine)
      ' Match_RegEx_In_RichTextBox(RichTextBox1, "Hello (World)", 0, Color.Red) ' Colored Result: "Hello World"
      ' Match_RegEx_In_RichTextBox(RichTextBox1, "Hello (World)", 1, Color.Red) ' Colored Result: "World"
   
   Private Sub Highlight_RegEx_In_RichTextBox(ByVal richtextbox As RichTextBox, _
                                          ByVal regex_pattern As String, _
                                          ByVal regex_group As Integer, _
                                          ByVal color As Color)

       Dim Matches = Regex.Match(richtextbox.Text, regex_pattern)

       Do While Matches.Success

           richtextbox.Select(Matches.Groups(regex_group).Index, Matches.Groups(regex_group).Length)
           RichTextBox1.SelectionColor = color
           Matches = Matches.NextMatch()

       Loop

       richtextbox.Select(richtextbox.TextLength, 0) ' Reset selection

        Matches = Nothing

   End Sub
   
   #End Region









Eleкtro

#292


· Obtiene el identificador de usuario (SID) de un usuario

Código (vbnet) [Seleccionar]
#Region " Username To SID "

   ' [ Username To SID ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   ' MsgBox(Username_To_SID("Administrador")) ' Result: S-1-5-21-3344876933-2114507426-1248549232-500

   Private Function Username_To_SID(ByVal Username As String) As String

       Dim SID As String = New System.Security.Principal.NTAccount(Username). _
                                      Translate(GetType(System.Security.Principal.SecurityIdentifier)).Value

       Return SID

   End Function

#End Region







· Obtiene la carpeta del perfil de usuario de un usuario.

Código (vbnet) [Seleccionar]
#Region " Username To ProfilePath "

   ' [ Username To ProfilePath ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   ' MsgBox(Username_To_ProfilePath("Administrador")) ' Result: C:\Users\Administrador

   Private Function Username_To_ProfilePath(ByVal Username As String) As String

       Dim SID As String = _
       New System.Security.Principal.NTAccount(Username). _
       Translate(GetType(System.Security.Principal.SecurityIdentifier)).Value

       Return My.Computer.Registry.GetValue( _
              "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & SID, _
              "ProfileImagePath", _
              "Unknown directory")

   End Function

#End Region








· Obtiene el nombre de usuario de un identificador de usuario (SID)

Código (vbnet) [Seleccionar]
#Region " SID To Username "

   ' [ SID To Username ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   ' MsgBox(SID_To_Username("S-1-5-21-3344876933-2114507426-1248549232-500")) ' Result: Administrador

   Private Function SID_To_UUsername(ByVal SID As String) As String

       Dim DomainName As String = New System.Security.Principal.SecurityIdentifier(SID). _
                                      Translate(GetType(System.Security.Principal.NTAccount)).Value

       Return DomainName.Substring(DomainName.IndexOf("\") + 1)

   End Function

#End Region







· Obtiene la carpeta del perfil de un usuario mediante un identificador de usuario (SID)

Código (vbnet) [Seleccionar]
#Region " SID To ProfilePath "

   ' [ SID To ProfilePath ]
   '
   ' // By Elektro H@cker
   '
   ' Examples:
   ' MsgBox(SID_To_ProfilePath("S-1-5-21-3344876933-2114507426-1248549232-500")) ' Result: "C:\Users\Administrador"

   Private Function SID_To_ProfilePath(ByVal SID As String) As String

       Return My.Computer.Registry.GetValue( _
              "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & SID, _
              "ProfileImagePath", _
              "Unknown directory")

   End Function

#End Region








Eleкtro

#293
· Colorear los items de un ListBox.


[youtube=640,360]http://www.youtube.com/watch?v=0W7iQMo1D1A[/youtube]


Código (vbnet) [Seleccionar]
#Region " [ListBox] Colorize Items "



' [ [ListBox] Colorize Items ]
'
' // By Elektro H@cker
'
' Examples :
'
' Set Drawmode to "OwnerDrawFixed" to make this work.
' ListBox1.DrawMode = DrawMode.OwnerDrawFixed
'
' Colorize only selected item:
' Colorize_Item(ListBox1, Colorize_ListBox_Items.Selected, Brushes.YellowGreen)
'
' Colorize all Non-Selected items
' Colorize_Item(ListBox1, Colorize_ListBox_Items.Non_Selected, Brushes.Red)
'
' Colorize all items:
' Colorize_Item(ListBox1, Colorize_ListBox_Items.All, Brushes.Yellow)
'
' Colorize any item:
' Colorize_Item(ListBox1, Colorize_ListBox_Items.None, Nothing)
'
' Colorize specific items:
' Colorize_Item(ListBox1, {0, (ListBox1.Items.Count \ 2), (ListBox1.Items.Count - 1)}, Brushes.HotPink)



    ' Stores the brush color to paint
    Dim ListBox_Color As Brush = Brushes.AliceBlue

    Private Enum Colorize_ListBox_Items As Short
        Selected = 0
        Non_Selected = 1
        All = 2
        None = 3
    End Enum

    Private Sub Colorize_Item(ByVal ListBox As ListBox, _
                              ByVal Items As Colorize_ListBox_Items, _
                              ByVal Brush_Color As Brush)

        ' Stores the Enum value
        ListBox.Tag = Items.ToString

        ' Stores the brush color
        ListBox_Color = Brush_Color

        ListBox.Invalidate() ' Refresh changes

    End Sub

    Private Sub Colorize_Item(ByVal ListBox As ListBox, _
                              ByVal Items As Integer(), _
                              ByVal Brush_Color As Brush)

        ' Stores the index items
        ListBox.Tag = String.Join(ChrW(Keys.Space), Items)

        ' Stores the brush color
        ListBox_Color = Brush_Color

        ListBox.Invalidate() ' Refresh changes

    End Sub

    Private Sub ListBox_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) _
    Handles ListBox1.DrawItem

        e.DrawBackground()

        Select Case sender.tag

            Case Colorize_ListBox_Items.Selected.ToString ' Colorize Selected Items

                If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
                    e.Graphics.FillRectangle(ListBox_Color, e.Bounds)
                End If

            Case Colorize_ListBox_Items.Non_Selected.ToString ' Colorize Non-Selected Items

                If (e.State And DrawItemState.Selected) = DrawItemState.None Then
                    e.Graphics.FillRectangle(ListBox_Color, e.Bounds)
                End If

            Case Colorize_ListBox_Items.All.ToString ' Colorize all

                e.Graphics.FillRectangle(ListBox_Color, e.Bounds)

            Case Colorize_ListBox_Items.None.ToString ' Colorize none

                Dim DefaultColor As SolidBrush = New SolidBrush(ListBox.DefaultBackColor)
                e.Graphics.FillRectangle(DefaultColor, e.Bounds)
                DefaultColor.Dispose()

            Case Else ' Colorize at specific index

                If Not String.IsNullOrEmpty(sender.tag) _
                AndAlso sender.tag.ToString.Split.Contains(e.Index.ToString) Then

                    e.Graphics.FillRectangle(ListBox_Color, e.Bounds)

                End If

        End Select

        Using b As New SolidBrush(e.ForeColor)
            e.Graphics.DrawString(ListBox1.GetItemText(ListBox1.Items(e.Index)), e.Font, b, e.Bounds)
        End Using

        e.DrawFocusRectangle()

    End Sub

#End Region








Eleкtro

· Una nueva versión de mi FileInfo personalizado, para obtener información sobre un archivo.

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

#Region " InfoFile "

        ' [ InfoFile ]
        '
        ' // By Elektro H@cker
        '
        ' Examples:
        '
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Name)) ' Result: Test
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Extension_Without_Dot)) ' Result: txt
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileName)) ' Result: Test.txt
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Directory)) ' Result: C:\
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.DriveRoot)) ' Result: C:\
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.DriveLetter)) ' Result: C
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FullName)) ' Result: C:\Test.txt
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.ShortName)) ' Result: Test.txt
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.ShortPath)) ' Result: C:\Test.txt
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Name_Length)) ' Result: 8
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Extension_Without_Dot_Length)) ' Result: 3
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileName_Length)) ' Result: 8
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Directory_Length)) ' Result: 3
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FullName_Length)) ' Result: 11
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileSize_Byte)) ' Result: 5.127.975
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileSize_KB)) ' Result: 5.007.79
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileSize_MB)) ' Result: 4,89
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileSize_GB)) ' Result: 0,00
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileSize_TB)) ' Result: 0,00
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.FileVersion)) ' Result: ""
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Attributes_Enum)) ' Result: 8224
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Attributes_String)) ' Result: Archive, NotContentIndexed
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.CreationTime)) ' Result: 16/09/2012  8:28:17
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.LastAccessTime)) ' Result: 16/09/2012 10:51:17
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.LastModifyTime)) ' Result: 16/09/2012 10:51:17
        ' MsgBox(InfoFile.Get_Info("C:\Test.txt", InfoFile.Info.Has_Extension)) ' Result: True

        Public Enum Info

            Name                  ' Filename without extension
            Extension_With_Dot    ' File-Extension (with dot included)
            Extension_Without_Dot ' File-Extension (without dot)
            FileName              ' Filename.extension
            Directory             ' Directory name
            FullName              ' Directory path + Filename

            DriveRoot             ' Drive letter
            DriveLetter           ' Drive letter (only 1 character)

            ShortName ' DOS8.3 Filename
            ShortPath ' DOS8.3 Path Name

            Name_Length                  ' Length of Filename without extension
            Extension_With_Dot_Length    ' Length of File-Extension (with dot included)
            Extension_Without_Dot_Length ' Length of File-Extension (without dot)
            FileName_Length              ' Length of Filename.extension
            Directory_Length             ' Length of Directory name
            FullName_Length              ' Length of Directory path + Filename

            FileSize_Byte ' Size in Bytes
            FileSize_KB   ' Size in KiloBytes
            FileSize_MB   ' Size in MegaBytes
            FileSize_GB   ' Size in GigaBytes
            FileSize_TB   ' Size in TeraBytes

            FileVersion ' Version for DLL or EXE files

            Attributes_Enum   ' Attributes as numbers
            Attributes_String ' Attributes as descriptions

            CreationTime   ' Date Creation time
            LastAccessTime ' Date Last Access time
            LastModifyTime ' Date Last Modify time

            Has_Extension  ' Checks if file have a file-extension.

        End Enum

        Public Shared Function Get_Info(ByVal File As String, ByVal Information As Info) As String

            Dim File_Info = My.Computer.FileSystem.GetFileInfo(File)

            Select Case Information

                Case Info.Name : Return File_Info.Name.Substring(0, File_Info.Name.LastIndexOf("."))
                Case Info.Extension_With_Dot : Return File_Info.Extension
                Case Info.Extension_Without_Dot : Return File_Info.Extension.Split(".").Last
                Case Info.FileName : Return File_Info.Name
                Case Info.Directory : Return File_Info.DirectoryName
                Case Info.DriveRoot : Return File_Info.Directory.Root.ToString
                Case Info.DriveLetter : Return File_Info.Directory.Root.ToString.Substring(0, 1)
                Case Info.FullName : Return File_Info.FullName
                Case Info.ShortName : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortName
                Case Info.ShortPath : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortPath
                Case Info.Name_Length : Return File_Info.Name.Length
                Case Info.Extension_With_Dot_Length : Return File_Info.Extension.Length
                Case Info.Extension_Without_Dot_Length : Return File_Info.Extension.Split(".").Last.Length
                Case Info.FileName_Length : Return File_Info.Name.Length
                Case Info.Directory_Length : Return File_Info.DirectoryName.Length
                Case Info.FullName_Length : Return File_Info.FullName.Length
                Case Info.FileSize_Byte : Return Convert.ToDouble(File_Info.Length).ToString("n0")
                Case Info.FileSize_KB : Return (Convert.ToDouble(File_Info.Length) / 1024L).ToString("n2")
                Case Info.FileSize_MB : Return (Convert.ToDouble(File_Info.Length) / 1024L ^ 2).ToString("n2")
                Case Info.FileSize_GB : Return (Convert.ToDouble(File_Info.Length) / 1024L ^ 3).ToString("n2")
                Case Info.FileSize_TB : Return (Convert.ToDouble(File_Info.Length) / 1024L ^ 4).ToString("n2")
                Case Info.FileVersion : Return CreateObject("Scripting.FileSystemObject").GetFileVersion(File)
                Case Info.Attributes_Enum : Return File_Info.Attributes
                Case Info.Attributes_String : Return File_Info.Attributes.ToString
                Case Info.CreationTime : Return File_Info.CreationTime
                Case Info.LastAccessTime : Return File_Info.LastAccessTime
                Case Info.LastModifyTime : Return File_Info.LastWriteTime
                Case Info.Has_Extension : Return IO.Path.HasExtension(File)

                Case Else : Return String.Empty

            End Select

        End Function

#End Region

    End Class







· Lo mismo de arriba pero para directorios:

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

#Region " InfoDir "

    ' [ InfoDir ]
    '
    ' // By Elektro H@cker
    '
    ' Examples:
    '
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.Name)) ' Result: Test
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.Parent)) ' Result: Test Parent
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FullName)) ' Result: C:\Test Parent\Test
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.DriveRoot)) ' Result: C:\
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.DriveLetter)) ' Result: C
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.Name_Length)) ' Result: 4
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FullName_Length)) ' Result: 19
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.Attributes_Enum)) ' Result: 8208
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.Attributes_String)) ' Result: Directory, NotContentIndexed
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.CreationTime)) ' Result: 16/09/2012  8:28:17
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.LastAccessTime)) ' Result: 16/09/2012 10:51:17
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.LastModifyTime)) ' Result: 16/09/2012 10:51:17
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FileSize_Byte)) ' Result: 5.127.975
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FileSize_KB)) ' Result: 5.007.79
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FileSize_MB)) ' Result: 4,89
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FileSize_GB)) ' Result: 0,00
    ' MsgBox(InfoDir.Get_Info("C:\Test Parent\Test", InfoDir.Info.FileSize_TB)) ' Result: 0,00

    Public Enum Info

        Name                  ' Folder name
        FullName              ' Directory path
        Parent                ' Parent directory

        DriveRoot             ' Drive letter
        DriveLetter           ' Drive letter (only 1 character)

        Name_Length                  ' Length of directory name
        FullName_Length              ' Length of full directory path

        FileSize_Byte ' Size in Bytes     (including subfolders)
        FileSize_KB   ' Size in KiloBytes (including subfolders)
        FileSize_MB   ' Size in MegaBytes (including subfolders)
        FileSize_GB   ' Size in GigaBytes (including subfolders)
        FileSize_TB   ' Size in TeraBytes (including subfolders)

        Attributes_Enum   ' Attributes as numbers
        Attributes_String ' Attributes as descriptions

        CreationTime   ' Date Creation time
        LastAccessTime ' Date Last Access time
        LastModifyTime ' Date Last Modify time

    End Enum

    Public Shared Function Get_Info(ByVal Dir As String, ByVal Information As Info) As String

        Dim Dir_Info = My.Computer.FileSystem.GetDirectoryInfo(Dir)

        Select Case Information

            Case Info.Name : Return Dir_Info.Name
            Case Info.FullName : Return Dir_Info.FullName
            Case Info.Parent : Return Dir_Info.Parent.ToString
            Case Info.DriveRoot : Return Dir_Info.Root.ToString
            Case Info.DriveLetter : Return Dir_Info.Root.ToString.Substring(0, 1)
            Case Info.Name_Length : Return Dir_Info.Name.Length
            Case Info.FullName_Length : Return Dir_Info.FullName.Length
            Case Info.FileSize_Byte : Return Convert.ToDouble(Get_Directory_Size(Dir_Info)).ToString("n0")
            Case Info.FileSize_KB : Return (Convert.ToDouble(Get_Directory_Size(Dir_Info)) / 1024L).ToString("n2")
            Case Info.FileSize_MB : Return (Convert.ToDouble(Get_Directory_Size(Dir_Info)) / 1024L ^ 2).ToString("n2")
            Case Info.FileSize_GB : Return (Convert.ToDouble(Get_Directory_Size(Dir_Info)) / 1024L ^ 3).ToString("n2")
            Case Info.FileSize_TB : Return (Convert.ToDouble(Get_Directory_Size(Dir_Info)) / 1024L ^ 4).ToString("n2")
            Case Info.Attributes_Enum : Return Dir_Info.Attributes
            Case Info.Attributes_String : Return Dir_Info.Attributes.ToString
            Case Info.CreationTime : Return Dir_Info.CreationTime
            Case Info.LastAccessTime : Return Dir_Info.LastAccessTime
            Case Info.LastModifyTime : Return Dir_Info.LastWriteTime

            Case Else : Return String.Empty

        End Select

    End Function

    Private Shared Function Get_Directory_Size(Directory As IO.DirectoryInfo) As Long
        Try
            Dim Dir_Total_Size As Long = Directory.EnumerateFiles().Sum(Function(file) file.Length)
            Dir_Total_Size += Directory.EnumerateDirectories().Sum(Function(dir) Get_Directory_Size(dir))
            Return Dir_Total_Size
        Catch
        End Try
        Return -1
    End Function

#End Region

End Class







Convierte bytes a otra unidad:

Código (vbnet) [Seleccionar]
#Region " Convert Bytes Function "

    ' [ Convert Bytes Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    '
    ' MsgBox(String.Format("{0} KB", Byte_To_Size(5127975, xByte.kilobyte, 2))) ' Result: 5007,79 KB
    ' MsgBox(String.Format("{0} MB", Byte_To_Size(5127975, xByte.megabyte, 2))) ' Result: 4,89 MB
    ' MsgBox(String.Format("{0} GB", Byte_To_Size(5127975, xByte.gigabyte, 3))) ' Result: 0,005 GB
    ' MsgBox(String.Format("{0} TB", Byte_To_Size(5127975, xByte.terabyte, 3))) ' Result: 0 TB
    ' MsgBox(String.Format("{0} PB", Byte_To_Size(5127975, xByte.petabyte, 3))) ' Result: 0 PB

    Enum xByte As Long
        kilobyte = 1024L
        megabyte = 1024L * kilobyte
        gigabyte = 1024L * megabyte
        terabyte = 1024L * gigabyte
        petabyte = 1024L * terabyte
    End Enum

    Private Function Byte_To_Size(ByVal bytes As Long, _
                                  ByVal convertto As xByte, _
                                  Optional ByVal decimals As Integer = 2 _
                                  ) As Double

        Return (Convert.ToDouble(bytes) / convertto).ToString("n" & decimals)

    End Function

#End Region








DarK_FirefoX

Este post, parece medio viejito, pero EXCELENTE APORTE. OJALA  LO HUBIERA VISTO ANTES....SAlu2s

Eleкtro

Cita de: DarK_FirefoX en 16 Septiembre 2013, 19:52 PMEste post, parece medio viejito, pero EXCELENTE APORTE. OJALA  LO HUBIERA VISTO ANTES....SAlu2s

Se agradece, pero es una pena que los .NETeros no estén muy interesados por mis publicaciones en este hilo :P

Un saludo!








ABDERRAMAH

Pues yo echo mano de este hilo de vez en cuando, hay cosas muy útiles.

Eleкtro

#298
Cita de: ABDERRAMAH en 17 Septiembre 2013, 02:59 AMPues yo echo mano de este hilo de vez en cuando, hay cosas muy útiles.

se agradece también!






·  Devuelve la conversión de bytes a la unidad de tamaño más aproximada

Por ejemplo, si le pasamos "60877579" bytes, nos devuelve este string: "58,06 MB"

Código (vbnet) [Seleccionar]
 #Region " Round Bytes "

   ' [ Round Bytes Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(Round_Bytes(1023))             ' Result: 1.023 Bytes
   ' MsgBox(Round_Bytes(80060, 1))         ' Result: 78,2 KB
   ' MsgBox(Round_Bytes(60877579))         ' Result: 58,06 MB
   ' MsgBox(Round_Bytes(4485888579))       ' Result: 4,18 GB
   ' MsgBox(Round_Bytes(20855564677579))   ' Result: 18,97 TB
   ' MsgBox(Round_Bytes(990855564677579))  ' Result: 901,18 PB
   ' MsgBox(Round_Bytes(1987464809247272)) ' Result: 1,77 PB

   Enum xByte As Long
       kilobyte = 1024L
       megabyte = 1024L * kilobyte
       gigabyte = 1024L * megabyte
       terabyte = 1024L * gigabyte
       petabyte = 1024L * terabyte
   End Enum

   Private Function Round_Bytes(ByVal bytes As Long, _
                                 Optional ByVal decimals As Integer = 2 _
                                 ) As String

       Select Case bytes

           Case Is >= xByte.petabyte
               Return String.Format("{0} PB", (Convert.ToDouble(bytes) / xByte.petabyte).ToString("n" & decimals))

           Case Is >= xByte.terabyte
               Return String.Format("{0} TB", (Convert.ToDouble(bytes) / xByte.terabyte).ToString("n" & decimals))

           Case Is >= xByte.gigabyte
               Return String.Format("{0} GB", (Convert.ToDouble(bytes) / xByte.gigabyte).ToString("n" & decimals))

           Case Is >= xByte.megabyte
               Return String.Format("{0} MB", (Convert.ToDouble(bytes) / xByte.megabyte).ToString("n" & decimals))

           Case Is >= xByte.kilobyte
               Return String.Format("{0} KB", (Convert.ToDouble(bytes) / xByte.kilobyte).ToString("n" & decimals))

           Case Is >= 0
               Return String.Format("{0} Bytes", Convert.ToDouble(bytes).ToString("n0"))

           Case Else
               Return String.Empty

       End Select

   End Function

#End Region








Eleкtro

#299
· FileSize Converter

Convierte tamaños de unidades de almacenamiento

Código (vbnet) [Seleccionar]
#Region " FileSize Converter "

    ' [ FileSize Converter Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    '
        ' MsgBox(String.Format("92928374 bytes = {0} Bytes", FileSize_Converter(92928374, Units.bytes, Units.bytes).ToString("n0"))) ' Result: 92.928.374,00 Bytes
        ' MsgBox(String.Format("92928374 bytes = {0} KB", FileSize_Converter(92928374, Units.bytes, Units.kilobyte).ToString("n2"))) ' Result: 90.750,37 KB
        ' MsgBox(String.Format("92928374 bytes = {0} MB", FileSize_Converter(92928374, Units.bytes, Units.megabyte).ToString("n2"))) ' Result: 88,62 MB
        ' MsgBox(String.Format("50 GB = {0} Bytes", FileSize_Converter(50, Units.gigabyte, Units.bytes).ToString("n2"))) ' Result: 53.687.091.200,00 Bytes
        ' MsgBox(String.Format("50 GB = {0} KB", FileSize_Converter(50, Units.gigabyte, Units.kilobyte).ToString("n2"))) ' Result: 52.428.800,00 KB
        ' MsgBox(String.Format("50 GB = {0} MB", FileSize_Converter(50, Units.gigabyte, Units.megabyte).ToString("n2"))) ' Result: 51,200,00 MB

    Enum Units As Long
        bytes = 1L
        kilobyte = 1024L
        megabyte = 1048576L
        gigabyte = 1073741824L
        terabyte = 1099511627776L
        petabyte = 1125899906842624L
    End Enum

    Private Function FileSize_Converter(ByVal Size As Long, _
                                  ByVal FromUnit As Units, _
                                  ByVal ToUnit As Units) As Double

        Dim bytes As Double = Convert.ToDouble(Size * FromUnit)
        Dim result As Double = 0

        If ToUnit < FromUnit Then

            Select Case ToUnit
                Case Units.bytes : result = bytes
                Case Units.kilobyte : result = bytes / Units.kilobyte
                Case Units.megabyte : result = bytes / Units.megabyte
                Case Units.gigabyte : result = bytes / Units.gigabyte
                Case Units.terabyte : result = bytes / Units.terabyte
                Case Units.petabyte : result = bytes / Units.petabyte
                Case Else : Return -1
            End Select

        ElseIf ToUnit > FromUnit Then

            Select Case ToUnit
                Case Units.bytes : result = bytes
                Case Units.kilobyte : result = bytes * Units.kilobyte / Units.kilobyte ^ 2
                Case Units.megabyte : result = bytes * Units.megabyte / Units.megabyte ^ 2
                Case Units.gigabyte : result = bytes * Units.gigabyte / Units.gigabyte ^ 2
                Case Units.terabyte : result = bytes * Units.terabyte / Units.terabyte ^ 2
                Case Units.petabyte : result = bytes * Units.petabyte / Units.petabyte ^ 2
                Case Else : Return -1
            End Select

        ElseIf ToUnit = FromUnit Then

            result = Size

        End If

        Return result

    End Function

#End Region