elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 4 Visitantes están viendo este tema.
Páginas: 1 2 3 4 5 6 7 [8] 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 533,732 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #70 en: 13 Abril 2013, 15:50 pm »

· Convierte entero a caracter

Código
  1. #Region " Byte To Char "
  2.  
  3.    ' [ Byte To Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Byte_To_Char(97)) ' Result: a
  9.  
  10.    Private Function Byte_To_Char(ByVal int As Int32) As String
  11.        Return Convert.ToChar(int)
  12.    End Function
  13.  
  14. #End Region



· Convierte caracter a entero

Código
  1. #Region " Char To Byte "
  2.  
  3.    ' [ Char To Byte Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Char_To_Byte("a")) ' Result: 97
  9.    ' Dim MyChar As String = "a" : MsgBox(Chr(Char_To_Byte(MyChar))) ' Result: a    ( ...xD )
  10.  
  11.    Private Function Char_To_Byte(ByVal str As String) As Int32
  12.        Dim character As Char = str & "c"
  13.        Return Convert.ToByte(character)
  14.    End Function
  15.  
  16. #End Region



· Obtiene el SHA1 de un string

Código
  1. #Region " Get SHA1 Of String "
  2.  
  3.    ' [ Get SHA1 Of String Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_String("Hello")) ' Result: D2EFCBBA102ED3339947E85F4141EB08926E40E9
  7.  
  8.    Private Function Get_SHA1_Of_String(ByVal str As String) As String
  9.        'create our SHA1 provider
  10.        Dim sha As System.Security.Cryptography.SHA1 = New System.Security.Cryptography.SHA1CryptoServiceProvider()
  11.        Dim hashedValue As String = String.Empty
  12.        'hash the data
  13.        Dim hashedData As Byte() = sha.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str))
  14.  
  15.        'loop through each byte in the byte array
  16.        For Each b As Byte In hashedData
  17.            'convert each byte and append
  18.            hashedValue += String.Format("{0,2:X2}", b)
  19.        Next
  20.  
  21.        'return the hashed value
  22.        Return hashedValue
  23.    End Function
  24.  
  25. #End Region



· Obtiene el SHA1 de un archivo

Código
  1. #Region " Get SHA1 Of File "
  2.  
  3.    ' [ Get SHA1 Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_SHA1_Of_File("C:\File.txt"))
  7.  
  8.    Private Function Get_SHA1_Of_File(ByVal File As String) As String
  9.        Dim File_Stream As New System.IO.FileStream(File, IO.FileMode.Open)
  10.        Dim sha As New System.Security.Cryptography.SHA1CryptoServiceProvider
  11.        Dim hash As Array
  12.        Dim shaHash As String
  13.        Dim sb As New System.Text.StringBuilder
  14.  
  15.        sha.ComputeHash(File_Stream)
  16.        hash = sha.Hash
  17.        For Each hashByte As Byte In hash : sb.Append(String.Format("{0:X1}", hashByte)) : Next
  18.        shaHash = sb.ToString
  19.        File_Stream.Close()
  20.  
  21.        Return shaHash
  22.    End Function
  23.  
  24. #End Region



· cifra un string en AES

Código
  1. #Region " AES Encrypt "
  2.  
  3.    ' [ AES Encrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Encrypt("Test_Text", "Test_Password")) ' Result: cv/vYwpl51/dxbxSMNSPSg==
  7.  
  8.    Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim encrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
  20.            Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
  21.            encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return encrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· descifra un string AES

Código
  1. #Region " AES Decrypt "
  2.  
  3.    ' [ AES Decrypt Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(AES_Decrypt("cv/vYwpl51/dxbxSMNSPSg==", "Test_Password")) ' Result: Test_Text
  7.  
  8.    Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
  9.        Dim AES As New System.Security.Cryptography.RijndaelManaged
  10.        Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
  11.        Dim decrypted As String = ""
  12.        Try
  13.            Dim hash(31) As Byte
  14.            Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
  15.            Array.Copy(temp, 0, hash, 0, 16)
  16.            Array.Copy(temp, 0, hash, 15, 16)
  17.            AES.Key = hash
  18.            AES.Mode = Security.Cryptography.CipherMode.ECB
  19.            Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
  20.            Dim Buffer As Byte() = Convert.FromBase64String(input)
  21.            decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
  22.            Return decrypted
  23.        Catch ex As Exception
  24.            Return Nothing
  25.        End Try
  26.    End Function
  27.  
  28. #End Region



· Devuelve el código fuente de una URL

Código
  1. #Region " Get URL SourceCode "
  2.  
  3.    ' [ Get URL SourceCode Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_URL_SourceCode("http://www.el-hacker.com"))
  7.  
  8.    Function Get_URL_SourceCode(ByVal url As String) As String
  9.  
  10.        Dim sourcecode As String = String.Empty
  11.  
  12.        Try
  13.            Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(url)
  14.            Dim response As System.Net.HttpWebResponse = request.GetResponse()
  15.            Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
  16.            sourcecode = sr.ReadToEnd()
  17.        Catch ex As Exception
  18.            MsgBox(ex.Message)
  19.        End Try
  20.  
  21.        Return sourcecode
  22.  
  23.    End Function
  24.  
  25. #End Region



· Intercambia entre el modo pantalla completa o modo normal.

Código
  1. #Region " Toogle FullScreen "
  2.  
  3.    ' [ Toogle FullScreen ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Toogle_FullScreen()
  9.  
  10.    Dim MyFormBorderStyle = Me.FormBorderStyle
  11.    Dim MyWindowState = Me.WindowState
  12.    Dim MyTopMost = Me.TopMost
  13.    Dim IsFullscreened As Boolean
  14.  
  15.    Public Sub Toogle_FullScreen()
  16.        If Not IsFullscreened Then
  17.            IsFullscreened = True
  18.            Me.FormBorderStyle = FormBorderStyle.None
  19.            Me.WindowState = FormWindowState.Maximized
  20.            Me.TopMost = True
  21.        ElseIf IsFullscreened Then
  22.            IsFullscreened = False
  23.            Me.FormBorderStyle = MyFormBorderStyle
  24.            Me.WindowState = MyWindowState
  25.            Me.TopMost = MyTopMost
  26.        End If
  27.    End Sub
  28.  
  29. #End Region



· Devuelve la versión del Framework con el que se ha desarrollado una applicación (o DLL).

Código
  1. #Region " Get FrameWork Of File "
  2.  
  3.    ' [ Get FrameWork Of File Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_FrameWork_Of_File("C:\My .Net Application.exe"))
  7.  
  8.    Private Function Get_FrameWork_Of_File(ByVal File As String) As String
  9.        Try
  10.            Dim FW As System.Reflection.Assembly = Reflection.Assembly.ReflectionOnlyLoadFrom(File)
  11.            Return FW.ImageRuntimeVersion
  12.        Catch ex As Exception
  13.            Return Nothing ' Is not managed code
  14.        End Try
  15.    End Function
  16.  
  17. #End Region



· Devuelve positivo si el número es primo

Código
  1. #Region " Number Is Prime? "
  2.  
  3.    ' [ Number Is Prime? Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Number_Is_Prime(4)) ' Result: False
  7.  
  8.    Private Function Number_Is_Prime(ByVal Number As Long, Optional ByVal f As Integer = 2) As Boolean
  9.        If Number = f Then Return True
  10.        If Number Mod f = 0 Or Number = 1 Then Return False _
  11.        Else Return Number_Is_Prime(Number, f + 1)
  12.    End Function
  13.  
  14. #End Region



· Valida si un string se puede usar como nombre de archivo en Windows

Código
  1. #Region " Validate Windows FileName "
  2.  
  3.    ' [ Validate Windows FileName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Validate_Windows_FileName("C:\Test.txt")) ' Result: True
  7.    ' MsgBox(Validate_Windows_FileName("C:\Te&st.txt")) ' Result: False
  8.  
  9.    Private Function Validate_Windows_FileName(ByRef FileName As String) As Boolean
  10.        Dim Windows_Reserved_Chars As String = "\/:*?""<>|"
  11.  
  12.        For i As Integer = 0 To FileName.Length - 1
  13.            If Windows_Reserved_Chars.Contains(FileName(i)) Then
  14.                Return False ' FileName is not valid
  15.            End If
  16.        Next
  17.  
  18.        Return True ' FileName is valid
  19.    End Function
  20.  
  21. #End Region



· cifra un string a Base64

Código
  1. #Region " String To Base64 "
  2.  
  3.    ' [ String To Base64 Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Base64("Test")) ' Result: VGVzdA==
  9.  
  10.    Private Function String_To_Base64(ByVal str As String) As String
  11.        Return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str))
  12.    End Function
  13.  
  14. #End Region



· descifra un string Base64 a string

Código
  1. #Region " Base64 To String "
  2.  
  3.    ' [ Base64 To String Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Base64_To_String("VGVzdA==")) ' Result: Test
  9.  
  10.    Private Function Base64_To_String(ByVal str As String) As String
  11.        Return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(str))
  12.    End Function
  13.  
  14. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #71 en: 13 Abril 2013, 17:29 pm »

· Devuelve la resolución de la pantalla primária o de la pantalla extendida

Código
  1. #Region " Get Screen Resolution "
  2.  
  3.    ' [ Get Screen Resolution Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Get_Screen_Resolution(False).ToString)
  9.    ' MsgBox(Get_Screen_Resolution(True).ToString)
  10.    ' Me.Size = Get_Screen_Resolution()
  11.  
  12.    Private Function Get_Screen_Resolution(ByVal Get_Extended_Screen_Resolution As Boolean) As Point
  13.  
  14.        If Not Get_Extended_Screen_Resolution Then
  15.            Return New Point(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
  16.        Else
  17.            Dim X As Integer, Y As Integer
  18.  
  19.            For Each screen As Screen In screen.AllScreens
  20.                X += screen.Bounds.Width
  21.                Y += screen.Bounds.Height
  22.            Next
  23.  
  24.            Return New Point(X, Y)
  25.        End If
  26.  
  27.    End Function
  28.  
  29. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #72 en: 13 Abril 2013, 18:23 pm »

· Enviar evento click del ratón.

Código
  1. #Region " Mouse Click "
  2.  
  3.    ' [ Mouse Click ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Click(MouseButton.Left)      ' Press the left click button
  9.    ' Mouse_Click(MouseButton.Left_Down) ' Hold the left click button
  10.    ' Mouse_Click(MouseButton.Left_Up)   ' Release the left click button
  11.  
  12.    Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)
  13.  
  14.    Public Enum MouseButton As Int32
  15.  
  16.        Left_Down = &H2    ' Left button (hold)
  17.        Left_Up = &H4      ' Left button (release)
  18.  
  19.        Right_Down = &H8   ' Right button (hold)
  20.        Right_Up = &H10    ' Right button (release)
  21.  
  22.        Middle_Down = &H20 ' Middle button (hold)
  23.        Middle_Up = &H40   ' Middle button (release)
  24.  
  25.        Left               ' Left   button (press)
  26.        Right              ' Right  button (press)
  27.        Middle             ' Middle button (press)
  28.  
  29.    End Enum
  30.  
  31.    Private Sub Mouse_Click(ByVal MouseButton As MouseButton)
  32.        Select Case MouseButton
  33.            Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
  34.            Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
  35.            Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
  36.            Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
  37.        End Select
  38.    End Sub
  39.  
  40. #End Region





· Setear la posición del mouse sin APIs y con posibilidad de restingir el movimiento a la pantalla primária.

Código
  1. #Region " Set Cursor Pos "
  2.  
  3.    ' [ Set Cursor Pos Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Set_Cursor_Pos(500, 500)
  9.    ' Set_Cursor_Pos(2500, 0, False)
  10.  
  11.    Private Sub Set_Cursor_Pos(ByVal X As Int32, ByVal Y As Int32, _
  12.                                    Optional ByVal Enable_Extended_Screen As Boolean = True)
  13.  
  14.        If Not Enable_Extended_Screen Then
  15.            Dim Screen_X = My.Computer.Screen.Bounds.Width
  16.            Dim Screen_Y = My.Computer.Screen.Bounds.Height
  17.            If X > Screen_X Then X = Screen_X
  18.            If Y > Screen_Y Then Y = Screen_Y
  19.        End If
  20.  
  21.        Cursor.Position = New System.Drawing.Point(X, Y)
  22.  
  23.    End Sub
  24.  
  25. #End Region





· Devuelve la posición del mouse en formato seleccionable

Código
  1. #Region " Get Cursor Pos "
  2.  
  3.    Public Enum Cursor_Data
  4.        AsText
  5.        AsPoint
  6.    End Enum
  7.  
  8.    ' [ Get Cursor Pos Function ]
  9.    '
  10.    ' // By Elektro H@cker
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsText))
  14.    ' MsgBox(Get_Cursor_Pos(Cursor_Data.AsPoint).ToString)
  15.  
  16.    Private Function Get_Cursor_Pos(ByVal Cursor_Data As Cursor_Data)
  17.        Select Case Cursor_Data
  18.            Case Cursor_Data.AsText : Return Cursor.Position.X & ", " & Cursor.Position.Y
  19.            Case Cursor_Data.AsPoint : Return Cursor.Position
  20.            Case Else : Return Nothing
  21.        End Select
  22.    End Function
  23.  
  24. #End Region



· Mueve el cursor

Código
  1. #Region " Mouse Move "
  2.  
  3.    ' [ Mouse Move ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' Mouse_Move(-50, 0) ' Move the cursor 50 pixels to left
  9.    ' Mouse_Move(+50, 0) ' Move the cursor 50 pixels to right
  10.    ' Mouse_Move(0, +50) ' Move the cursor 50 pixels to down
  11.    ' Mouse_Move(0, -50) ' Move the cursor 50 pixels to up
  12.  
  13.    Public Enum MouseMove_Event As Int32
  14.        Move = &H1
  15.    End Enum
  16.  
  17.    Public Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseMove_Event, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)
  18.  
  19.    Private Sub Mouse_Move(ByVal X As Int32, ByVal Y As Int32)
  20.        Mouse_Event(&H1, X, Y, 0, 0)
  21.    End Sub
  22.  
  23. #End Region
« Última modificación: 13 Abril 2013, 18:27 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #73 en: 15 Abril 2013, 16:11 pm »

· Descomprimir con la librería SevenzipSharp:

EDITO: Mejorado (Extracción con password)

Código
  1. #Region " SevenZipSharp Extract "
  2.  
  3.    ' [ SevenZipSharp Extract Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Extract("C:\File.7zip")                  ' Will be extracted in the same dir.
  14.    ' SevenZipSharp_Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\".
  15.    ' SevenZipSharp_Extract("C:\File.7zip", , "Password")    ' Will be extracted with the given password.
  16.  
  17.    Imports SevenZip
  18.    Dim dll As String = "7z.dll"
  19.  
  20.    Private Function SevenZipSharp_Extract(ByVal InputFile As String, _
  21.                                           Optional ByVal OutputDir As String = Nothing, _
  22.                                           Optional ByVal Password As String = "Nothing") As Boolean
  23.  
  24.        Try
  25.            ' Set library path
  26.            SevenZipExtractor.SetLibraryPath(dll)
  27.  
  28.            ' Create extractor and specify the file to extract
  29.            Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password)
  30.  
  31.            ' Specify the output path where the files will be extracted
  32.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  33.  
  34.            ' Add Progress Handler
  35.            ' AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress
  36.  
  37.            ' Check for password matches
  38.            If Extractor.Check() Then
  39.                ' Start the extraction
  40.                Extractor.BeginExtractArchive(OutputDir)
  41.            Else
  42.                Return False ' Bad password
  43.            End If
  44.  
  45.            Return True ' File extracted
  46.  
  47.            Extractor.Dispose()
  48.  
  49.        Catch ex As Exception
  50.            'Return False ' File not extracted
  51.            Throw New Exception(ex.Message)
  52.        End Try
  53.  
  54.    End Function
  55.  
  56.    ' Public Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  57.    '     MsgBox("Percent extracted: " & e.PercentDone)
  58.    ' End Sub
  59.  
  60. #End Region





· Comprimir con la librería SevenzipSharp:

EDITO: Mejorado (Compresión con password)

Código
  1. #Region " SevenZipSharp Compress "
  2.  
  3.    ' [ SevenZipSharp Compress Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' SevenZipSharp_Compress("C:\File.txt")                          ' File will be compressed in the same dir.
  14.    ' SevenZipSharp_Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Extracted\".
  15.    ' SevenZipSharp_Compress("C:\Folder\", , , , , , "Password")     ' File will be compressed with the given password.
  16.    ' SevenZipSharp_Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra)
  17.  
  18.    Imports SevenZip
  19.    Dim dll As String = "7z.dll"
  20.  
  21.    Private Function SevenZipSharp_Compress(ByVal Input_DirOrFile As String, _
  22.                                       Optional ByVal OutputFileName As String = Nothing, _
  23.                                       Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
  24.                                       Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
  25.                                       Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
  26.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  27.                                       Optional ByVal Password As String = Nothing) As Boolean
  28.        Try
  29.            ' Set library path
  30.            SevenZipExtractor.SetLibraryPath(dll)
  31.  
  32.            ' Create compressor and specify the file or folder to compress
  33.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  34.  
  35.            ' Set compression parameters
  36.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  37.            Compressor.CompressionMethod = CompressionMethod ' Append files to compressed file or overwrite the compressed file.
  38.            Compressor.ArchiveFormat = Format ' Compression file format
  39.            Compressor.CompressionMode = CompressionMode ' Compression mode
  40.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  41.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  42.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  43.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  44.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  45.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  46.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  47.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  48.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  49.  
  50.            ' Get File extension
  51.            Dim CompressedFileExtension As String = Nothing
  52.            Select Case Compressor.ArchiveFormat
  53.                Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
  54.                Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
  55.                Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
  56.                Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
  57.                Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
  58.                Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
  59.            End Select
  60.  
  61.            ' Add Progress Handler
  62.            'AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  63.  
  64.            ' Removes the end slash ("\") if given for a directory
  65.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  66.  
  67.            ' Generate the OutputFileName if any is given.
  68.            If OutputFileName Is Nothing Then _
  69.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")
  70.  
  71.            ' Check if given argument is Dir or File ...then start the compression
  72.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  73.                If Not Password Is Nothing Then
  74.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  75.                Else
  76.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  77.                End If
  78.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  79.                If Not Password Is Nothing Then
  80.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  81.                Else
  82.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  83.                End If
  84.            End If
  85.  
  86.        Catch ex As Exception
  87.            'Return False ' File not compressed
  88.            Throw New Exception(ex.Message)
  89.        End Try
  90.  
  91.        Return True ' File compressed
  92.  
  93.    End Function
  94.  
  95.    ' Public Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  96.    '     MsgBox("Percent compressed: " & e.PercentDone)
  97.    ' End Sub
  98.  
  99. #End Region
« Última modificación: 15 Abril 2013, 17:46 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #74 en: 15 Abril 2013, 16:43 pm »

· Devuelve información sobre archivos comprimidos (tamaño, nombre de los archivos internos, total de archivos internos..)

Código
  1. #Region " SevenZipSharp FileInfo "
  2.  
  3.    ' [ SevenZipSharp FileInfo Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Instructions :
  8.    ' 1. Add a reference to "SevenZipSharp.dll".
  9.    ' 2. Add the "7z.dll" or "7z64.dll" files to the project.
  10.    ' 3. Use the code below.
  11.    '
  12.    ' Examples :
  13.    ' MsgBox(SevenZipSharp_FileInfo("C:\Test.7z", SevenZip_Info.Format))
  14.    ' For Each FileName In SevenZipSharp_FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next
  15.  
  16.    Imports SevenZip
  17.    Dim dll As String = "7z.dll"
  18.  
  19.    Public Enum SevenZip_Info
  20.        FileName
  21.        Format
  22.        Size_In_Bytes
  23.        Internal_Files_FileNames
  24.        Total_Internal_Files
  25.    End Enum
  26.  
  27.    Private Function SevenZipSharp_FileInfo(ByVal InputFile As String, ByVal Info As SevenZip_Info)
  28.  
  29.        Try
  30.            ' Set library path
  31.            SevenZip.SevenZipExtractor.SetLibraryPath(dll)
  32.  
  33.            ' Create extractor and specify the file to extract
  34.            Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile)
  35.  
  36.            ' Return info
  37.            Select Case Info
  38.  
  39.                Case SevenZip_Info.FileName
  40.                    Return Extractor.FileName
  41.  
  42.                Case SevenZip_Info.Format
  43.                    Return Extractor.Format
  44.  
  45.                Case SevenZip_Info.Size_In_Bytes
  46.                    Return Extractor.PackedSize
  47.  
  48.                Case SevenZip_Info.Total_Internal_Files
  49.                    Return Extractor.FilesCount
  50.  
  51.                Case SevenZip_Info.Internal_Files_FileNames
  52.                    Dim FileList As New List(Of String)
  53.                    For Each Internal_File In Extractor.ArchiveFileData
  54.                        FileList.Add(Internal_File.FileName)
  55.                    Next
  56.                    Return FileList
  57.  
  58.                Case Else
  59.                    Return Nothing
  60.  
  61.            End Select
  62.  
  63.            Extractor.Dispose()
  64.  
  65.        Catch ex As Exception
  66.            ' Return nothing
  67.            Throw New Exception(ex.Message)
  68.        End Try
  69.  
  70.    End Function
  71.  
  72. #End Region
« Última modificación: 15 Abril 2013, 16:45 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #75 en: 15 Abril 2013, 17:52 pm »

Una función muy simple, elimina el último caracter de un string, puede ahorrar bastante escritura de código a veces...

Código
  1. #Region " Remove Last Char "
  2.  
  3.    ' [ Remove Last Char Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(Remove_Last_Char("C:\Folder\"))
  9.    ' Var = Remove_Last_Char(Var)
  10.  
  11.    Private Function Remove_Last_Char(ByVal str As String) As String
  12.        Return str.Substring(0, str.Length - 1)
  13.    End Function
  14.  
  15. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #76 en: 15 Abril 2013, 18:12 pm »

· Convierte un string a LowerCase/Titlecase/UpperCase/WordCase

Código
  1. #Region " String to Case "
  2.  
  3.    ' [ String to Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase))
  9.    ' Var = String_To_WordCase(Var, StringCase.LowerCase)
  10.  
  11.    Public Enum StringCase
  12.        LowerCase
  13.        Titlecase
  14.        UpperCase
  15.        WordCase
  16.    End Enum
  17.  
  18.    Private Function String_To_Case(ByVal str As String, ByVal StringCase As StringCase) As String
  19.        Select Case StringCase
  20.            Case Form1.StringCase.LowerCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(str)
  21.            Case Form1.StringCase.Titlecase : Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase)
  22.            Case Form1.StringCase.UpperCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(str)
  23.            Case Form1.StringCase.WordCase : Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str)
  24.            Case Else : Return Nothing
  25.        End Select
  26.    End Function
  27.  
  28. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #77 en: 16 Abril 2013, 12:06 pm »

La función de convertir un string a Case, mejorada y mucho más ampliada:

Código
  1. #Region " String to Case "
  2.  
  3.    ' [ String to Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.Titlecase))
  9.    ' MsgBox(String_To_Case("THiS is a TeST", StringCase.DelimitedCase_Lower, ";"))
  10.    ' Var = String_To_WordCase(Var, StringCase.LowerCase)
  11.  
  12.    Public Enum StringCase
  13.  
  14.        LowerCase
  15.        UpperCase
  16.        Titlecase
  17.        WordCase
  18.  
  19.        CamelCase_First_Lower
  20.        CamelCase_First_Upper
  21.  
  22.        MixedCase_First_Lower
  23.        MixedCase_First_Upper
  24.        MixedCase_Word_Lower
  25.        MixedCase_Word_Upper
  26.  
  27.        DelimitedCase_Lower
  28.        DelimitedCase_Mixed_Word_Lower
  29.        DelimitedCase_Mixed_Word_Upper
  30.        DelimitedCase_Title
  31.        DelimitedCase_Upper
  32.        DelimitedCase_Word
  33.  
  34.    End Enum
  35.  
  36.    Private Function String_To_Case(ByVal str As String, _
  37.                                    ByVal StringCase As StringCase, _
  38.                                    Optional ByVal Delimiter As String = "-") As String
  39.        Select Case StringCase
  40.  
  41.            Case StringCase.LowerCase
  42.                Return str.ToLower
  43.  
  44.            Case StringCase.UpperCase
  45.                Return str.ToUpper
  46.  
  47.            Case StringCase.Titlecase
  48.                Return Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase)
  49.  
  50.            Case StringCase.WordCase
  51.                Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str)
  52.  
  53.            Case StringCase.CamelCase_First_Lower
  54.                Return Char.ToLower(str(0)) & _
  55.                    System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1)
  56.  
  57.            Case StringCase.CamelCase_First_Upper
  58.                Return Char.ToUpper(str(0)) & _
  59.                    System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str).Replace(" ", "").Substring(1)
  60.  
  61.            Case StringCase.MixedCase_First_Lower
  62.                Dim MixedString As String = Nothing
  63.                For X As Integer = 0 To str.Length - 1
  64.                    Dim c As Char = str(X)
  65.                    If (X / 2).ToString.Contains(",") Then _
  66.                         MixedString += c.ToString.ToUpper _
  67.                    Else MixedString += c.ToString.ToLower
  68.                Next
  69.                Return MixedString
  70.  
  71.            Case StringCase.MixedCase_First_Upper
  72.                Dim MixedString As String = Nothing
  73.                For X As Integer = 0 To str.Length - 1
  74.                    Dim c As Char = str(X)
  75.                    If (X / 2).ToString.Contains(",") Then _
  76.                         MixedString += c.ToString.ToLower _
  77.                    Else MixedString += c.ToString.ToUpper
  78.                Next
  79.                Return MixedString
  80.  
  81.            Case StringCase.MixedCase_Word_Lower
  82.                Dim MixedString As String = Nothing
  83.                Dim Count As Integer = 1
  84.                For X As Integer = 0 To str.Length - 1
  85.                    Dim c As Char = str(X)
  86.                    If Not c = " " Then Count += 1 Else Count = 1
  87.                    If (Count / 2).ToString.Contains(",") Then _
  88.                         MixedString += c.ToString.ToUpper _
  89.                    Else MixedString += c.ToString.ToLower
  90.                Next
  91.                Return MixedString
  92.  
  93.            Case StringCase.MixedCase_Word_Upper
  94.                Dim MixedString As String = Nothing
  95.                Dim Count As Integer = 1
  96.                For X As Integer = 0 To str.Length - 1
  97.                    Dim c As Char = str(X)
  98.                    If Not c = " " Then Count += 1 Else Count = 1
  99.                    If (Count / 2).ToString.Contains(",") Then _
  100.                         MixedString += c.ToString.ToLower _
  101.                    Else MixedString += c.ToString.ToUpper
  102.                Next
  103.                Return MixedString
  104.  
  105.            Case StringCase.DelimitedCase_Lower
  106.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  107.                Return rgx.Replace(str.ToLower, Delimiter)
  108.  
  109.            Case StringCase.DelimitedCase_Upper
  110.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  111.                Return rgx.Replace(str.ToUpper, Delimiter)
  112.  
  113.            Case StringCase.DelimitedCase_Title
  114.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  115.                Return rgx.Replace(Char.ToUpper(str(0)) + StrConv(str.Substring(1), VbStrConv.Lowercase), Delimiter)
  116.  
  117.            Case StringCase.DelimitedCase_Word
  118.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  119.                Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str), Delimiter)
  120.  
  121.            Case StringCase.DelimitedCase_Mixed_Word_Lower
  122.                Dim MixedString As String = Nothing
  123.                Dim Count As Integer = 1
  124.                For X As Integer = 0 To str.Length - 1
  125.                    Dim c As Char = str(X)
  126.                    If Not c = " " Then Count += 1 Else Count = 1
  127.                    If (Count / 2).ToString.Contains(",") Then _
  128.                         MixedString += c.ToString.ToUpper _
  129.                    Else MixedString += c.ToString.ToLower
  130.                Next
  131.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  132.                Return rgx.Replace(MixedString, Delimiter)
  133.  
  134.            Case StringCase.DelimitedCase_Mixed_Word_Upper
  135.                Dim MixedString As String = Nothing
  136.                Dim Count As Integer = 1
  137.                For X As Integer = 0 To str.Length - 1
  138.                    Dim c As Char = str(X)
  139.                    If Not c = " " Then Count += 1 Else Count = 1
  140.                    If (Count / 2).ToString.Contains(",") Then _
  141.                         MixedString += c.ToString.ToLower _
  142.                    Else MixedString += c.ToString.ToUpper
  143.                Next
  144.                Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  145.                Return rgx.Replace(MixedString, Delimiter)
  146.  
  147.            Case Else
  148.                Return Nothing
  149.  
  150.        End Select
  151.  
  152.    End Function
  153.  
  154. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #78 en: 16 Abril 2013, 15:31 pm »

· Un AppActivate distinto, en mi opinión mejor, se usa por el nombre del proceso, con posibilidad de seleccionar el proceso por el título de la ventana de dicho proceso:

Código
  1. #Region " Activate APP "
  2.  
  3.    ' [ Activate APP Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' ActivateAPP("notepad.exe")
  9.    ' ActivateAPP("notepad.exe", "Notepad Sub-Window Title")
  10.    ' MsgBox(ActivateAPP("notepad"))
  11.  
  12.    Private Function ActivateAPP(ByVal ProcessName As String, _
  13.                                 Optional ByVal WindowTitle As String = Nothing) As Boolean
  14.  
  15.        If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
  16.        Dim ProcessTitle As String = Nothing
  17.        Dim ProcessArray = Process.GetProcessesByName(ProcessName)
  18.  
  19.        If ProcessArray.Length = 0 Then : Return False ' ProcessName not found
  20.  
  21.        ElseIf ProcessArray.Length > 1 AndAlso Not WindowTitle Is Nothing Then
  22.            For Each Title In ProcessArray
  23.                If Title.MainWindowTitle.Contains(WindowTitle) Then _
  24.                   ProcessTitle = Title.MainWindowTitle
  25.            Next
  26.  
  27.        Else : ProcessTitle = ProcessArray(0).MainWindowTitle
  28.        End If
  29.  
  30.        AppActivate(ProcessTitle)
  31.        Return True ' Window activated
  32.  
  33.    End Function
  34.  
  35. #End Region




· Escribe texto en un Log

Código
  1. #Region " Write Log "
  2.  
  3.    ' [ Write Log Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' WriteLog("Application started", InfoType.Information)
  9.    ' WriteLog("Application got mad", InfoType.Critical)
  10.  
  11.    Dim LogFile = CurDir() & "\" & System.Reflection.Assembly.GetExecutingAssembly.GetName().Name & ".log"
  12.  
  13.    Public Enum InfoType
  14.        Information
  15.        Exception
  16.        Critical
  17.        None
  18.    End Enum
  19.  
  20.    Private Function WriteLog(ByVal Message As String, ByVal InfoType As InfoType) As Boolean
  21.        Dim LocalDate As String = My.Computer.Clock.LocalTime.ToString.Split(" ").First
  22.        Dim LocalTime As String = My.Computer.Clock.LocalTime.ToString.Split(" ").Last
  23.        Dim LogDate As String = "[ " & LocalDate & " ] " & " [ " & LocalTime & " ]  "
  24.        Dim MessageType As String = Nothing
  25.  
  26.        Select Case InfoType
  27.            Case InfoType.Information : MessageType = "Information: "
  28.            Case InfoType.Exception : MessageType = "Error: "
  29.            Case InfoType.Critical : MessageType = "Critical: "
  30.            Case InfoType.None : MessageType = ""
  31.        End Select
  32.  
  33.        Try
  34.            My.Computer.FileSystem.WriteAllText(LogFile, vbNewLine & LogDate & MessageType & Message & vbNewLine, True)
  35.            Return True
  36.        Catch ex As Exception
  37.            'Return False
  38.            Throw New Exception(ex.Message)
  39.        End Try
  40.  
  41.    End Function
  42.  
  43. #End Region





· Cierra un proceso (No lo mata)

Código
  1. #Region " Close Process Function "
  2.  
  3.    ' [ Close Process Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Close_Process(Application.ExecutablePath)
  8.    ' Close_Process("notepad.exe")
  9.    ' Close_Process("notepad", False)
  10.  
  11.    Private Function Close_Process(ByRef Process_Name As String, _
  12.                                   Optional ByVal OnlyFirstFound As Boolean = True) As Boolean
  13.  
  14.        If Process_Name.ToLower.EndsWith(".exe") Then Process_Name = Process_Name.Substring(0, Process_Name.Length - 4)
  15.        Dim proc() As Process = Process.GetProcessesByName(Process_Name)
  16.  
  17.        If Not OnlyFirstFound Then
  18.            For proc_num As Integer = 0 To proc.Length - 1
  19.                Try : proc(proc_num).CloseMainWindow() _
  20.                    : Catch : Return False : End Try ' One of the processes can't be closed
  21.            Next
  22.            Return True
  23.        Else
  24.            Try : proc(0).CloseMainWindow() : Return True ' Close message sent to the process
  25.            Catch : Return False : End Try ' Can't close the process
  26.        End If
  27.  
  28.        Return Nothing ' ProcessName not found
  29.  
  30.    End Function
  31.  
  32. #End Region





· Buscar coincidencias de texto usando expresiones regulares

Código
  1. #Region " Find RegEx "
  2.  
  3.    ' [ Find RegEx Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' If Find_RegEx("abcdef", "^[A-Z]+$") Then MsgBox("Yes") Else MsgBox("No") ' Result: No
  9.    ' If Find_RegEx("abcdef", "^[A-Z]+$", True) Then MsgBox("Yes") Else MsgBox("No") ' Result: Yes
  10.  
  11.    Private Function Find_RegEx(ByVal str As String, ByVal Pattern As String, _
  12.                                 Optional ByVal Ignorecase As Boolean = False) As Boolean
  13.  
  14.        Dim RegExCase As System.Text.RegularExpressions.RegexOptions
  15.  
  16.        If Ignorecase Then _
  17.             RegExCase = System.Text.RegularExpressions.RegexOptions.IgnoreCase _
  18.        Else RegExCase = System.Text.RegularExpressions.RegexOptions.None
  19.  
  20.        Dim RegEx As New System.Text.RegularExpressions.Regex(Pattern, RegExCase)
  21.  
  22.        Return RegEx.IsMatch(str)
  23.  
  24.    End Function
  25.  
  26. #End Region





· Leer un texto línea por línea (For each line...) con posibilidad de saltar líneas en blanco.

Código
  1. #Region " Read TextFile Libe By Line "
  2.  
  3.    ' [ Read TextFile Libe By Line ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Read_TextFile_Libe_By_Line("C:\Test.txt")
  9.    ' Read_TextFile_Libe_By_Line("C:\Test.txt", True)
  10.  
  11.    Private Sub Read_TextFile_Libe_By_Line(ByVal TextFile As String, _
  12.                                           Optional ByVal Read_Blank_Lines As Boolean = False)
  13.        Dim Line As String = Nothing
  14.        Dim Text As IO.StreamReader = IO.File.OpenText(TextFile)
  15.        Dim RegEx As New System.Text.RegularExpressions.Regex("^\s+$")
  16.  
  17.        Do Until Text.EndOfStream
  18.  
  19.            Line = Text.ReadLine()
  20.  
  21.            If (Not Read_Blank_Lines _
  22.                AndAlso _
  23.               (Not Line = "" _
  24.                And Not RegEx.IsMatch(Line))) _
  25.                OrElse Read_Blank_Lines Then
  26.                ' Do things here...
  27.                MsgBox(Line)
  28.            End If
  29.  
  30.        Loop
  31.  
  32.        Text.Close() : Text.Dispose()
  33.  
  34.    End Sub
  35.  
  36. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.885



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #79 en: 16 Abril 2013, 16:38 pm »

· Devuelve el valor de un nombre de un Enum

Código
  1. #Region " Get Enum Value "
  2.  
  3.    ' [ Get Enum Value Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_Enum_Value(DayOfWeek.Sunday)) ' Result: 0
  7.    ' MsgBox(Get_Enum_Value(DayOfWeek.Monday)) ' Result: 1
  8.  
  9.    Function Get_Enum_Value(Of T)(Byval ValueName As T) As Int32
  10.        Return Convert.ToInt32(ValueName)
  11.    End Function
  12.  
  13. #End Region




· Devuelve el nombre de un valor de un Enum

Código
  1. #Region " Get Enum Name "
  2.  
  3.    ' [ Get Enum ValueName Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Get_Enum_Name(Of DayOfWeek)(0)) ' Result: Sunday
  7.    ' MsgBox(Get_Enum_Name(Of DayOfWeek)(1)) ' Result: Monday
  8.  
  9.    Private Function Get_Enum_Name(Of T)(EnumValue As Integer) As String
  10.        Return [Enum].GetName(GetType(T), EnumValue)
  11.    End Function
  12.  
  13. #End Region





· Comparar dos archivos:

Código
  1. #Region " Compare Files "
  2.  
  3.    ' [ Compare Files Function ]
  4.    '
  5.    ' Examples :
  6.    ' MsgBox(Compare_Files("C:\File1.txt", "C:\File2.txt"))
  7.  
  8.    Private Function Compare_Files(ByVal File1 As String, ByVal File2 As String) As Boolean
  9.  
  10.        ' Set to true if the files are equal; false otherwise
  11.        Dim FilesAreEqual As Boolean = False
  12.  
  13.        With My.Computer.FileSystem
  14.  
  15.            ' Ensure that the files are the same length before comparing them line by line.
  16.            If .GetFileInfo(File1).Length = .GetFileInfo(File2).Length Then
  17.                Using file1Reader As New FileStream(File1, FileMode.Open), _
  18.                      file2Reader As New FileStream(File2, FileMode.Open)
  19.                    Dim byte1 As Integer = file1Reader.ReadByte()
  20.                    Dim byte2 As Integer = file2Reader.ReadByte()
  21.  
  22.                    ' If byte1 or byte2 is a negative value, we have reached the end of the file.
  23.                    While byte1 >= 0 AndAlso byte2 >= 0
  24.                        If (byte1 <> byte2) Then
  25.                            FilesAreEqual = False
  26.                            Exit While
  27.                        Else
  28.                            FilesAreEqual = True
  29.                        End If
  30.  
  31.                        ' Read the next byte.
  32.                        byte1 = file1Reader.ReadByte()
  33.                        byte2 = file2Reader.ReadByte()
  34.                    End While
  35.  
  36.                End Using
  37.            End If
  38.        End With
  39.  
  40.        Return FilesAreEqual
  41.    End Function
  42.  
  43. #End Region
En línea



Páginas: 1 2 3 4 5 6 7 [8] 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines