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

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Mensajes
Páginas: 1 ... 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 [913] 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 ... 1236
9121  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 8 Mayo 2013, 20:34 pm
Con esta Class pueden manejar la aplicación BoxedAppPacker en tiempo de ejecución para empaquetar otros proyectos .NET (u otro tipo de executables) para virtualizarlos.
PD: Se necesita la aplicación BoxedAppPacker v3.XXX (versión de consola), la class no usa el SDK.

Código
  1. #Region " BoxedAppPacker "
  2.  
  3. ' [ BoxedAppPacker Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions:
  8. ' 1. Add the "BoxedAppPackerConsole.exe" to the project
  9. ' 2. Add the "BoxedAppPacker Class" Class to the project
  10. '
  11. ' Examples:
  12. '
  13. ' -----------------
  14. ' Pack Single File:
  15. ' -----------------
  16. ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe")
  17. ' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe", True, True, True, True, True, BoxedAppPacker.BoxedAppPackerVariables.ExeDir)
  18. '
  19. ' ---------------------------------
  20. ' Pack File And Include More Files:
  21. ' ---------------------------------
  22. ' BoxedAppPacker.Pack_File_And_Include_More_Files("C:\Windows\Explorer.exe", {"C:\Windows\system32\shell32.dll", "C:\Windows\system32\notepad.exe"}, "C:\Virtual Explorer.exe", True, True, True)
  23.  
  24.  
  25. #Region " BoxedAppPacker Class "
  26.  
  27. Public Class BoxedAppPacker
  28.  
  29.    ''' <summary>
  30.    ''' The BoxedAppPackerConsole.exe location.
  31.    ''' </summary>
  32.    Public Shared BoxedAppPacker_Location As String = ".\BoxedAppPackerConsole.exe"
  33.  
  34.    ''' <summary>
  35.    ''' Boxed App Packer Variables To Override CommandLine.
  36.    ''' </summary>
  37.    Public Enum BoxedAppPackerVariables
  38.        ExeDir ' a directory that contains the packed exe.
  39.        CurDir ' current directory .
  40.        ProgramFiles ' ProgramFiles environment variable.
  41.        Temp ' Temp environment variable.
  42.        BoxedAppVar_ExeFileName ' exe's file name (for example, "notepad.exe")
  43.        BoxedAppVar_ExeFileExtension ' exe's file extension (for example, "exe")
  44.        BoxedAppVar_ExeFileNameWithoutExtension ' exe's file name without extension (for example, "notepad")
  45.        BoxedAppVar_ExeFullPath ' exe's full path (for example, "C_\notepad.exe")
  46.        BoxedAppVar_OldCmdLine ' a command line specified when the packed exe started, you can use it to add additional arguments, for example: <BoxedAppVar:OldCmdLine> /NewSwitch
  47.        BoxedAppVar_OldArgs ' a command line specified when the packed exe started without the exe path, for example "<BoxedAppVar:ExeFullPath>" /C virtual.cmd <BoxedAppVar:OldArgs>, Usage: packed.exe Arg1 Arg2, It works as: original.exe /C virtual.cmd Arg1 Arg2
  48.    End Enum
  49.  
  50.    ''' <summary>
  51.    ''' Virtualize a single executable.
  52.    ''' </summary>
  53.    Public Shared Function Pack_Single_File(ByVal File As String, ByVal OutputFile As String, _
  54.                                    Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
  55.                                    Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
  56.                                    Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
  57.                                    Optional ByVal Enable_Virtual_Registry As Boolean = True, _
  58.                                    Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
  59.                                    Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
  60.                                    ) As Boolean
  61.  
  62.        If Not Check_InputExecutable(File) Then Return False
  63.  
  64.        Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")
  65.  
  66.        Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
  67.                                                     & File & _
  68.                                                     """ dest=""" _
  69.                                                     & OutputFile & _
  70.                                                     """ cmd_line_overridden=""" _
  71.                                                     & Enable_CommandLine_Arguments & _
  72.                                                     """ cmd_args=""&lt;" _
  73.                                                     & CommandLine_Variable_Formatted & _
  74.                                                     "&gt;"" share_virtual_environment_with_child_processes=""" _
  75.                                                     & Share_Virtual_Environment_With_Child_Processes & _
  76.                                                     """ enable_debug_log=""false"" " & _
  77.                                                     "enable_virtual_registry=""" _
  78.                                                     & Enable_Virtual_Registry & _
  79.                                                     """ hide_virtual_files_from_file_dialog=""" _
  80.                                                     & Hide_Virtual_Files_From_File_Dialog & _
  81.                                                     """ all_changes_are_virtual=""" _
  82.                                                     & Make_All_File_And_Registry_Changes_Virtual & """>"
  83.  
  84.        Dim BoxedProject_File_Section As String = <a><![CDATA[
  85.  
  86.  <files>
  87.    <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  88.      <files/>
  89.    </file>
  90.    <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  91.      <files>
  92.        <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  93.          <files/>
  94.        </file>
  95.      </files>
  96.    </file>
  97.  </files>
  98. ]]></a>.Value
  99.  
  100.        Dim BoxedProject_Registry_Section As String = <a><![CDATA[
  101.  <registry>
  102.    <keys>
  103.      <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
  104.        <values/>
  105.        <keys/>
  106.      </key>
  107.      <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
  108.        <values/>
  109.        <keys/>
  110.      </key>
  111.      <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
  112.        <values/>
  113.        <keys/>
  114.      </key>
  115.      <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
  116.        <values/>
  117.        <keys/>
  118.      </key>
  119.      <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
  120.        <values/>
  121.        <keys/>
  122.      </key>
  123.    </keys>
  124.  </registry>
  125. </project>
  126. ]]></a>.Value
  127.  
  128.        Try
  129.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
  130.                TextFile.WriteLine(BoxedProject_Options_Section)
  131.            End Using
  132.  
  133.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", True, System.Text.Encoding.ASCII)
  134.                TextFile.WriteLine(BoxedProject_File_Section)
  135.                TextFile.WriteLine(BoxedProject_Registry_Section)
  136.            End Using
  137.  
  138.            Dim BoxedAppPacker_Console As New Process()
  139.            Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()
  140.  
  141.            BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
  142.            BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
  143.            BoxedAppPacker_Console_Info.CreateNoWindow = True
  144.            BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
  145.            BoxedAppPacker_Console_Info.UseShellExecute = False
  146.            BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
  147.            BoxedAppPacker_Console.Start()
  148.            BoxedAppPacker_Console.WaitForExit()
  149.  
  150.            If BoxedAppPacker_Console.ExitCode <> 0 Then
  151.                Return False
  152.            Else
  153.                Return True
  154.            End If
  155.        Catch ex As Exception
  156.            ' MsgBox(ex.Message)
  157.            Return False
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Virtualize a executable and include more files.
  164.    ''' </summary>
  165.    Public Shared Function Pack_File_And_Include_More_Files(ByVal File As String, ByVal SubFiles() As String, ByVal OutputFile As String, _
  166.                                Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
  167.                                Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
  168.                                Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
  169.                                Optional ByVal Enable_Virtual_Registry As Boolean = True, _
  170.                                Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
  171.                                Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
  172.                                ) As Boolean
  173.  
  174.        If Not Check_InputExecutable(File) Then Return False
  175.  
  176.        Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")
  177.  
  178.        Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
  179.                                                     & File & _
  180.                                                     """ dest=""" _
  181.                                                     & OutputFile & _
  182.                                                     """ cmd_line_overridden=""" _
  183.                                                     & Enable_CommandLine_Arguments & _
  184.                                                     """ cmd_args=""&lt;" _
  185.                                                     & CommandLine_Variable_Formatted & _
  186.                                                     "&gt;"" share_virtual_environment_with_child_processes=""" _
  187.                                                     & Share_Virtual_Environment_With_Child_Processes & _
  188.                                                     """ enable_debug_log=""false"" " & _
  189.                                                     "enable_virtual_registry=""" _
  190.                                                     & Enable_Virtual_Registry & _
  191.                                                     """ hide_virtual_files_from_file_dialog=""" _
  192.                                                     & Hide_Virtual_Files_From_File_Dialog & _
  193.                                                     """ all_changes_are_virtual=""" _
  194.                                                     & Make_All_File_And_Registry_Changes_Virtual & """>"
  195.  
  196.        ' Generate File Section Start
  197.        Dim BoxedProject_File_Section_Start As String = <a><![CDATA[
  198.  
  199.  <files>
  200.    <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  201.      <files>
  202. ]]></a>.Value
  203.  
  204.        ' Generate SubFiles Tags Section
  205.        Dim FileCount As Int16 = 0
  206.        Dim SubFile_Tag As String = Nothing
  207.  
  208.        For SubFile As Integer = 1 To SubFiles.Count
  209.            Application.DoEvents()
  210.            FileCount += 1
  211.  
  212.            If FileCount = 1 Then
  213.                SubFile_Tag += <a><![CDATA[
  214.        <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
  215.          <files/>
  216. ]]></a>.Value
  217.            Else
  218.                SubFile_Tag += <a><![CDATA[
  219.        </file>
  220.        <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
  221.          <files/>
  222. ]]></a>.Value
  223.            End If
  224.  
  225.        Next
  226.  
  227.        ' Generate File Section End
  228.        Dim BoxedProject_File_Section_End As String = <a><![CDATA[
  229.        </file>
  230.      </files>
  231.    </file>
  232.    <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  233.      <files>
  234.        <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
  235.          <files/>
  236.        </file>
  237.      </files>
  238.    </file>
  239.  </files>
  240. ]]></a>.Value
  241.  
  242.        ' Generate Registry Section
  243.        Dim BoxedProject_Registry_Section As String = <a><![CDATA[
  244.  <registry>
  245.    <keys>
  246.      <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
  247.        <values/>
  248.        <keys/>
  249.      </key>
  250.      <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
  251.        <values/>
  252.        <keys/>
  253.      </key>
  254.      <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
  255.        <values/>
  256.        <keys/>
  257.      </key>
  258.      <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
  259.        <values/>
  260.        <keys/>
  261.      </key>
  262.      <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
  263.        <values/>
  264.        <keys/>
  265.      </key>
  266.    </keys>
  267.  </registry>
  268. </project>
  269. ]]></a>.Value
  270.  
  271.        Try
  272.  
  273.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
  274.                TextFile.WriteLine(BoxedProject_Options_Section)
  275.                TextFile.WriteLine(BoxedProject_File_Section_Start)
  276.                TextFile.WriteLine(SubFile_Tag)
  277.                TextFile.WriteLine(BoxedProject_File_Section_End)
  278.                TextFile.WriteLine(BoxedProject_Registry_Section)
  279.            End Using
  280.  
  281.            Dim BoxedAppPacker_Console As New Process()
  282.            Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()
  283.  
  284.            BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
  285.            BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
  286.            BoxedAppPacker_Console_Info.CreateNoWindow = True
  287.            BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
  288.            BoxedAppPacker_Console_Info.UseShellExecute = False
  289.            BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
  290.            BoxedAppPacker_Console.Start()
  291.            BoxedAppPacker_Console.WaitForExit()
  292.  
  293.            If BoxedAppPacker_Console.ExitCode <> 0 Then
  294.                Return False
  295.            Else
  296.                Return True
  297.            End If
  298.        Catch ex As Exception
  299.            ' MsgBox(ex.Message)
  300.            Return False
  301.        End Try
  302.  
  303.    End Function
  304.  
  305.    ' Checks if InputFile exist and also is a executable.
  306.    Private Shared Function Check_InputExecutable(ByVal File As String) As Boolean
  307.        If Not IO.File.Exists(File) Then
  308.            MsgBox("File don't exist.")
  309.            Return False
  310.        End If
  311.        If Not File.ToLower.EndsWith(".exe") Then
  312.            MsgBox("Not a valid executable file.")
  313.            Return False
  314.        End If
  315.        Return True
  316.    End Function
  317.  
  318. End Class
  319.  
  320. #End Region
  321.  
  322. #End Region
9122  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 8 Mayo 2013, 17:14 pm
¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !

Ya puedes descargar la colección completa de 290 snippets útiles.

PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...

http://elektrostudios.tk/Snippets.zip
9123  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 8 Mayo 2013, 17:02 pm
El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?
¿Incluido donde?, ¿en el archivo del recopilatorio comprimido?, a que te refieres, el código lo tienes en la página 7.

Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me haya encontrado, salu2
No hay reglas, puedes publicar tanto código própio como ajeno,
lo importante que hay que tener en cuenta es que séa código re-usable y no código hardcodeado.

un saludo!

EDITO:

Man tu tienes todos los codes que publicas alli dentro del compactado ??
Si, todos los codes que yo he publicado es porque he necesitado usarlos, y me guardo una copia que puedes encontrar en el post principal.
9124  Programación / Scripting / Re: Tutorial comando Set!!! [batch] en: 8 Mayo 2013, 14:17 pm
@lmarza
No revivas posts de hace 4 años, gracias.

Ya dispones de una variable con ese formato:
Código:
Echo %DATE%
9125  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 8 Mayo 2013, 11:14 am
Una class con funciones para realizar todo tipo de operaciones en el Registro de Windows:

- Crear clave
- Eliminar clave
- Crear valor
- Eliminar valor
- Obtener los datos de un valor
- Exportar clave
- Importar archivo
- Saltar a clave (abrir Regedit en clave específica)
- Comprobar si un valor existe
- Comprobar si los datos de un valor están vacíos
- Copiar clave a otro lugar del registro
- Copiar valor a otro lugar del registro
- Establecer permisos de usuario para una clave

Código
  1. #Region " RegEdit "
  2.  
  3. ' [ RegEdit Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples :
  8. '
  9. ' -----------
  10. ' Create Key:
  11. ' -----------
  12. ' RegEdit.Create_Key("HKCU\Software\MyProgram")                        ' Creates "HKCU\Software\MyProgram"
  13. ' RegEdit.Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings"
  14. '
  15. ' -----------
  16. ' Delete Key:
  17. ' -----------
  18. ' RegEdit.Delete_Key("HKLM\Software\7-zip")                ' Deletes the "7-zip" tree including subkeys
  19. ' RegEdit.Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys
  20. '
  21. ' -------------
  22. ' Delete Value:
  23. ' -------------
  24. ' RegEdit.Delete_Value("HKCU\Software\7-Zip", "Lang")               ' Deletes "Lang" Value
  25. ' RegEdit.Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value
  26. '
  27. ' ----------
  28. ' Get Value:
  29. ' ----------
  30. ' Dim Data As String = RegEdit.Get_Value("HKCU\Software\MyProgram", "Value name"))
  31. ' Dim Data As String = RegEdit.Get_Value("HKEY_CURRENT_USER\Software\MyProgram", "Value name"))
  32. '
  33. ' ----------
  34. ' Set Value:
  35. ' ----------
  36. ' RegEdit.Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String)               ' Create/Replace "Value Name" with "Data" as string data
  37. ' RegEdit.Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data
  38. '
  39. ' -----------
  40. ' Export Key:
  41. ' -----------
  42. ' RegEdit.Export_Key("HKLM", "C:\HKLM.reg")                  ' Export entire "HKEY_LOCAL_MACHINE" Tree to "C:\HKLM.reg" file.
  43. ' RegEdit.Export_Key("HKLM\Software\7-zip\", "C:\7-zip.reg") ' Export entire "7-zip" Tree to "C:\7-zip.reg" file.
  44. '
  45. ' ------------
  46. ' Import File:
  47. ' ------------
  48. ' RegEdit.Import_RegFile("C:\Registry_File.reg") ' Install a registry file.
  49. '
  50. ' ------------
  51. ' Jump To Key:
  52. ' ------------
  53. ' RegEdit.Jump_To_Key("HKLM")                               ' Opens Regedit at "HKEY_LOCAL_MACHINE" Root.
  54. ' RegEdit.Jump_To_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Opens Regedit at "HKEY_LOCAL_MACHINE\Software\7-zip" tree.
  55. '
  56. ' -------------
  57. ' Exist Value?:
  58. ' -------------
  59. ' MsgBox(RegEdit.Exist_Value("HKLM\software\7-zip", "Path") ' Checks if "Path" value exist.
  60. '
  61. ' ------------
  62. ' Exist Data?:
  63. ' ------------
  64. ' MsgBox(RegEdit.Exist_Data("HKLM\software\7-zip", "Path") ' Checks if "Path" value have empty data.
  65. '
  66. ' ---------
  67. ' Copy Key:
  68. ' ---------
  69. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip")          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  70. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip")         ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip"
  71. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing)          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\"
  72. ' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing)             ' Copies "HKCU\Software\7-Zip" to "HKLM\"
  73. ' RegEdit.Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\")  ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
  74. '
  75. ' -----------
  76. ' Copy Value:
  77. ' -----------
  78. ' RegEdit.Copy_Value("HKLM\software\7-zip", "path", "HKLM\software\7-zip", "path_backup") ' Copies "Path" value with their data to "HKLM\software\7-zip" "path_backup".
  79. '
  80. ' -----------
  81. ' Set_UserAccess_Key:
  82. ' -----------
  83. ' RegEdit.Set_UserAccess_Key("HKCU\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access})
  84. ' RegEdit.Set_UserAccess_Key("HKEY_CURRENT_USER\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access, RegEdit.RegUserAccess.Creator_Full_Access, RegEdit.RegUserAccess.System_Full_Access})
  85.  
  86. #Region " RegEdit Class "
  87.  
  88. Public Class RegEdit
  89.  
  90.    ''' <summary>
  91.    ''' Create a new registry key.
  92.    ''' </summary>
  93.    Public Shared Function Create_Key(ByVal RegKey As String) As Boolean
  94.  
  95.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  96.        Dim KeyPath As String = Get_Key_Path(RegKey)
  97.  
  98.        Try
  99.            RootKey.CreateSubKey(KeyPath)
  100.            RootKey.Close()
  101.            RootKey.Dispose()
  102.            Return True
  103.        Catch ex As Exception
  104.            ' MsgBox(ex.Message)
  105.            ' Throw New Exception(ex.Message)
  106.            Return False
  107.        End Try
  108.  
  109.    End Function
  110.  
  111.    ''' <summary>
  112.    ''' Delete a registry key.
  113.    ''' </summary>
  114.    Public Shared Function Delete_Key(ByVal RegKey As String) As Boolean
  115.  
  116.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  117.        Dim KeyPath As String = Get_Key_Path(RegKey)
  118.  
  119.        Try
  120.            RootKey.DeleteSubKeyTree(KeyPath)
  121.            RootKey.Close()
  122.            RootKey.Dispose()
  123.            Return True
  124.        Catch ex As Exception
  125.            ' MsgBox(ex.Message)
  126.            ' Throw New Exception(ex.Message)
  127.            Return False
  128.        End Try
  129.  
  130.    End Function
  131.  
  132.    ''' <summary>
  133.    ''' Delete a registry key.
  134.    ''' </summary>
  135.    Public Shared Function Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  136.  
  137.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  138.        Dim KeyPath As String = Get_Key_Path(RegKey)
  139.  
  140.        Try
  141.            RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue)
  142.            RootKey.Close()
  143.            RootKey.Dispose()
  144.            Return True
  145.        Catch ex As Exception
  146.            ' MsgBox(ex.Message)
  147.            ' Throw New Exception(ex.Message)
  148.            Return False
  149.        End Try
  150.  
  151.    End Function
  152.  
  153.    ''' <summary>
  154.    ''' Get the data of a registry value.
  155.    ''' </summary>
  156.    Public Shared Function Get_Value(ByVal RegKey As String, ByVal RegValue As String) As String
  157.  
  158.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  159.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  160.  
  161.        Try
  162.            Return My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing)
  163.        Catch ex As Exception
  164.            ' MsgBox(ex.Message)
  165.            ' Throw New Exception(ex.Message)
  166.            Return False
  167.        End Try
  168.    End Function
  169.  
  170.    ''' <summary>
  171.    ''' Set the data of a registry value.
  172.    ''' If the Key or value don't exist it will be created automatically.
  173.    ''' </summary>
  174.    Public Shared Function Set_Value(ByVal RegKey As String, _
  175.                                     ByVal RegValue As String, _
  176.                                     ByVal RegData As String, _
  177.                                     ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean
  178.  
  179.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  180.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  181.  
  182.        Try
  183.            If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then
  184.                My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary)
  185.            Else
  186.                My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType)
  187.            End If
  188.            Return True
  189.        Catch ex As Exception
  190.            ' MsgBox(ex.Message)
  191.            ' Throw New Exception(ex.Message)
  192.            Return False
  193.        End Try
  194.  
  195.    End Function
  196.  
  197.    ''' <summary>
  198.    ''' Export a registry key (including sub-keys) to a file.
  199.    ''' </summary>
  200.    Public Shared Function Export_Key(ByVal RegKey As String, ByVal OutputFile As String) As Boolean
  201.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  202.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  203.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  204.  
  205.        Try
  206.            Dim Regedit As New Process()
  207.            Dim Regedit_Info As New ProcessStartInfo()
  208.  
  209.            Regedit_Info.FileName = "Reg.exe"
  210.            Regedit_Info.Arguments = "Export " & """" & KeyPath & """" & " " & """" & OutputFile & """" & " /y"
  211.            Regedit_Info.CreateNoWindow = True
  212.            Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
  213.            Regedit_Info.UseShellExecute = False
  214.            Regedit.StartInfo = Regedit_Info
  215.            Regedit.Start()
  216.            Regedit.WaitForExit()
  217.  
  218.            If Regedit.ExitCode <> 0 Then
  219.                Return False
  220.            Else
  221.                Return True
  222.            End If
  223.  
  224.        Catch ex As Exception
  225.            ' MsgBox(ex.Message)
  226.            ' Throw New Exception(ex.Message)
  227.            Return False
  228.        End Try
  229.  
  230.    End Function
  231.  
  232.    ''' <summary>
  233.    ''' Import a registry file.
  234.    ''' </summary>
  235.    Public Shared Function Import_RegFile(ByVal RegFile As String) As Boolean
  236.  
  237.        If IO.File.Exists(RegFile) Then
  238.  
  239.            Try
  240.                Dim Regedit As New Process()
  241.                Dim Regedit_Info As New ProcessStartInfo()
  242.  
  243.                Regedit_Info.FileName = "Reg.exe"
  244.                Regedit_Info.Arguments = "Import " & """" & RegFile & """"
  245.                Regedit_Info.CreateNoWindow = True
  246.                Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
  247.                Regedit_Info.UseShellExecute = False
  248.                Regedit.StartInfo = Regedit_Info
  249.                Regedit.Start()
  250.                Regedit.WaitForExit()
  251.  
  252.                If Regedit.ExitCode <> 0 Then
  253.                    Return False
  254.                Else
  255.                    Return True
  256.                End If
  257.  
  258.            Catch ex As Exception
  259.                ' MsgBox(ex.Message)
  260.                ' Throw New Exception(ex.Message)
  261.                Return False
  262.            End Try
  263.  
  264.        Else
  265.            ' MsgBox("File don't exist")
  266.            Return False
  267.  
  268.        End If
  269.  
  270.    End Function
  271.  
  272.    ''' <summary>
  273.    ''' Open Regedit at specific key.
  274.    ''' </summary>
  275.    Public Shared Function Jump_To_Key(ByVal RegKey As String) As Boolean
  276.  
  277.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  278.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  279.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  280.  
  281.        Try
  282.            Set_Value("HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", "" & KeyPath & "", Microsoft.Win32.RegistryValueKind.String)
  283.            Process.Start("Regedit.exe")
  284.            Return True
  285.        Catch ex As Exception
  286.            ' MsgBox(ex.Message)
  287.            ' Throw New Exception(ex.Message)
  288.            Return False
  289.        End Try
  290.  
  291.    End Function
  292.  
  293.    ''' <summary>
  294.    ''' Check if a value exist.
  295.    ''' </summary>
  296.    Public Shared Function Exist_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  297.  
  298.        Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
  299.        Dim KeyPath As String = Get_Key_Path(RegKey)
  300.  
  301.        Try
  302.            If RootKey.OpenSubKey(KeyPath, False).GetValue(RegValue) = String.Empty Then
  303.                Return False
  304.            Else
  305.                Return True
  306.            End If
  307.        Catch ex As Exception
  308.            ' MsgBox(ex.Message)
  309.            ' Throw New Exception(ex.Message)
  310.            Return False
  311.        End Try
  312.  
  313.    End Function
  314.  
  315.    ''' <summary>
  316.    ''' Check if a value have empty data.
  317.    ''' </summary>
  318.    Public Shared Function Exist_Data(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  319.  
  320.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  321.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  322.  
  323.        Try
  324.            If My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing) = Nothing Then
  325.                Return False
  326.            Else
  327.                Return True
  328.            End If
  329.        Catch ex As Exception
  330.            ' MsgBox(ex.Message)
  331.            ' Throw New Exception(ex.Message)
  332.            Return False
  333.        End Try
  334.  
  335.    End Function
  336.  
  337.    ''' <summary>
  338.    ''' Copy a key tree to another location of the registry.
  339.    ''' </summary>
  340.    Public Shared Function Copy_Key(ByVal OldRootKey As String, _
  341.                        ByVal OldPath As String, _
  342.                        ByVal OldName As String, _
  343.                        ByVal NewRootKey As String, _
  344.                        ByVal NewPath As String, _
  345.                        ByVal NewName As String) As Boolean
  346.  
  347.        If OldPath Is Nothing Then OldPath = ""
  348.        If NewRootKey Is Nothing Then NewRootKey = OldRootKey
  349.        If NewPath Is Nothing Then NewPath = ""
  350.        If NewName Is Nothing Then NewName = ""
  351.  
  352.        If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1)
  353.        If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1)
  354.  
  355.        If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1)
  356.        If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1)
  357.        If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1)
  358.        If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1)
  359.  
  360.        If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1)
  361.        If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1)
  362.        If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1)
  363.        If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1)
  364.  
  365.        Dim OrigRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(OldRootKey)
  366.        Dim DestRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(NewRootKey)
  367.  
  368.        Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True)
  369.        Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName)
  370.        Reg_Copy_SubKeys(oldkey, newkey)
  371.        Return True
  372.    End Function
  373.  
  374.    Private Shared Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey)
  375.  
  376.        Dim ValueNames As String() = OrigKey.GetValueNames()
  377.        Dim SubKeyNames As String() = OrigKey.GetSubKeyNames()
  378.  
  379.        For i As Integer = 0 To ValueNames.Length - 1
  380.            Application.DoEvents()
  381.            DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i)))
  382.        Next
  383.  
  384.        For i As Integer = 0 To SubKeyNames.Length - 1
  385.            Application.DoEvents()
  386.            Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i)))
  387.        Next
  388.  
  389.    End Sub
  390.  
  391.    ''' <summary>
  392.    ''' Copy a value with their data to another location of the registry.
  393.    ''' If the Key don't exist it will be created automatically.
  394.    ''' </summary>
  395.    Public Shared Function Copy_Value(ByVal RegKey As String, ByVal RegValue As String, _
  396.                                      ByVal NewRegKey As String, ByVal NewRegValue As String) As Boolean
  397.  
  398.        Dim OldRootKey As String = Get_Root_Key(RegKey).ToString
  399.        Dim OldKeyPath As String = OldRootKey & "\" & Get_Key_Path(RegKey)
  400.  
  401.        Dim NewRootKey As String = Get_Root_Key(NewRegKey).ToString
  402.        Dim NewKeyPath As String = NewRootKey & "\" & Get_Key_Path(NewRegKey)
  403.  
  404.        Dim RegData = Get_Value(OldKeyPath, RegValue)
  405.  
  406.        Try
  407.            Set_Value(NewKeyPath, NewRegValue, RegData, Microsoft.Win32.RegistryValueKind.Unknown)
  408.            Return True
  409.        Catch ex As Exception
  410.            ' MsgBox(ex.Message)
  411.            ' Throw New Exception(ex.Message)
  412.            Return False
  413.        End Try
  414.  
  415.    End Function
  416.  
  417.    ''' <summary>
  418.    ''' Valid User identifiers for Regini.exe command.
  419.    ''' </summary>
  420.    Public Enum RegUserAccess As Short
  421.        Administrators_Full_Access = 1
  422.        Administrators_Read_Access = 2
  423.        Administrators_Read_and_Write_Access = 3
  424.        Administrators_Read_Write_and_Delete_Access4
  425.        Administrators_Read_Write_and_Execute_Access = 20
  426.        Creator_Full_Access = 5
  427.        Creator_Read_and_Write_Access = 6
  428.        Interactive_User_Full_Access = 21
  429.        Interactive_User_Read_and_Write_Access = 22
  430.        Interactive_User_Read_Write_and_Delete_Access = 23
  431.        Power_Users_Full_Access = 11
  432.        Power_Users_Read_and_Write_Access = 12
  433.        Power_Users_Read_Write_and_Delete_Access = 13
  434.        System_Full_Access = 17
  435.        System_Operators_Full_Access = 14
  436.        System_Operators_Read_and_Write_Access = 15
  437.        System_Operators_Read_Write_and_Delete_Access = 16
  438.        System_Read_Access = 19
  439.        System_Read_and_Write_Access = 18
  440.        World_Full_Access = 7
  441.        World_Read_Access = 8
  442.        World_Read_and_Write_Access = 9
  443.        World_Read_Write_and_Delete_Access = 10
  444.    End Enum
  445.  
  446.    ''' <summary>
  447.    ''' Modify the User permissions of a registry key.
  448.    ''' </summary>
  449.    Public Shared Function Set_UserAccess_Key(ByVal RegKey As String, ByVal RegUserAccess() As RegUserAccess) As Boolean
  450.  
  451.        Dim PermissionString As String = Nothing
  452.        Dim RootKey As String = Get_Root_Key(RegKey).ToString
  453.  
  454.        Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
  455.        If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)
  456.  
  457.        For Each user In RegUserAccess
  458.            Application.DoEvents()
  459.            PermissionString += " " & user
  460.        Next
  461.  
  462.        PermissionString = "[" & PermissionString & "]"
  463.        PermissionString = PermissionString.Replace("[ ", "[")
  464.  
  465.        Try
  466.  
  467.            Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "Regini.ini", False, System.Text.Encoding.ASCII)
  468.                TextFile.WriteLine("""" & KeyPath & """" & " " & PermissionString)
  469.            End Using
  470.  
  471.            Dim Regini As New Process()
  472.            Dim Regini_Info As New ProcessStartInfo()
  473.  
  474.            Regini_Info.FileName = "Regini.exe"
  475.  
  476.  
  477.            MsgBox(PermissionString)
  478.            MsgBox("Regini.exe " & """" & System.IO.Path.GetTempPath() & "Regini.ini" & """")
  479.  
  480.  
  481.            Regini_Info.Arguments = """" & System.IO.Path.GetTempPath() & "Regini.ini" & """"
  482.            Regini_Info.CreateNoWindow = True
  483.            Regini_Info.WindowStyle = ProcessWindowStyle.Hidden
  484.            Regini_Info.UseShellExecute = False
  485.            Regini.StartInfo = Regini_Info
  486.            Regini.Start()
  487.            Regini.WaitForExit()
  488.  
  489.            If Regini.ExitCode <> 0 Then
  490.                Return False
  491.            Else
  492.                Return True
  493.            End If
  494.  
  495.        Catch ex As Exception
  496.            ' MsgBox(ex.Message)
  497.            ' Throw New Exception(ex.Message)
  498.            Return False
  499.        End Try
  500.  
  501.    End Function
  502.  
  503.    ' Returns the RootKey formatted
  504.    Private Shared Function Get_Root_Key(ByVal RegKey As String) As Microsoft.Win32.RegistryKey
  505.        Select Case RegKey.ToUpper.Split("\").First
  506.            Case "HKCR", "HKEY_CLASSES_ROOT" : Return Microsoft.Win32.Registry.ClassesRoot
  507.            Case "HKCC", "HKEY_CURRENT_CONFIG" : Return Microsoft.Win32.Registry.CurrentConfig
  508.            Case "HKCU", "HKEY_CURRENT_USER" : Return Microsoft.Win32.Registry.CurrentUser
  509.            Case "HKLM", "HKEY_LOCAL_MACHINE" : Return Microsoft.Win32.Registry.LocalMachine
  510.            Case "HKEY_PERFORMANCE_DATA" : Return Microsoft.Win32.Registry.PerformanceData
  511.            Case Else : Return Nothing
  512.        End Select
  513.    End Function
  514.  
  515.    ' Returns the KeyPath formatted
  516.    Private Shared Function Get_Key_Path(ByVal RegKey As String) As String
  517.        Dim KeyPath As String = String.Empty
  518.        For i As Integer = 1 To RegKey.Split("\").Length - 1
  519.            Application.DoEvents()
  520.            KeyPath += RegKey.Split("\")(i) & "\"
  521.        Next
  522.  
  523.        If Not KeyPath.Contains("\") Then KeyPath = KeyPath & "\"
  524.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  525.  
  526.        Return KeyPath
  527.    End Function
  528.  
  529. End Class
  530.  
  531. #End Region
  532.  
  533. #End Region
9126  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 7 Mayo 2013, 21:08 pm
Una class para trabajar con StringCases por ejemplo para renombrar archivos de forma masiva a TitleCase,
contiene las funciones que posteé hace un tiempo, y le he añadido el "InvertedCase".

Código
  1. #Region " StringCase Class "
  2.  
  3. Public Class StringCase
  4.  
  5.    ' [ StringCase Functions ]
  6.    '
  7.    ' // By Elektro H@cker
  8.    '
  9.    ' Examples :
  10.    ' MsgBox(StringCase.Titlecase("THiS is a TeST"))
  11.    ' MsgBox(StringCase.DelimitedCase_Lower("THiS is a TeST", ";"))
  12.    ' MsgBox(StringCase.InvertedCase("HeLLo"))
  13.    ' Var = StringCase.WordCase(Var)
  14.  
  15.    ''' <summary>
  16.    ''' Convert to LowerCase [Ex: ab cd ef]
  17.    ''' </summary>
  18.    Public Shared Function LowerCase(ByVal Text As String) As String
  19.        Return Text.ToLower
  20.    End Function
  21.  
  22.    ''' <summary>
  23.    ''' Convert to UpperCase [Ex: AB CD EF]
  24.    ''' </summary>
  25.    Public Shared Function UpperCase(ByVal Text As String) As String
  26.        Return Text.ToUpper
  27.    End Function
  28.  
  29.    ''' <summary>
  30.    ''' Convert to Titlecase [Ex: Ab cd ef]
  31.    ''' </summary>
  32.    Public Shared Function Titlecase(ByVal Text As String) As String
  33.        Return Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase)
  34.    End Function
  35.  
  36.    ''' <summary>
  37.    ''' Convert to WordCase [Ex: Ab Cd Ef]
  38.    ''' </summary>
  39.    Public Shared Function WordCase(ByVal Text As String) As String
  40.        Return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text)
  41.    End Function
  42.  
  43.    ''' <summary>
  44.    ''' Convert to CamelCase (And first letter to Lower) [Ex: abCdEf]
  45.    ''' </summary>
  46.    Public Shared Function CamelCase_First_Lower(ByVal Text As String) As String
  47.        Return Char.ToLower(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1)
  48.    End Function
  49.  
  50.    ''' <summary>
  51.    ''' Convert to CamelCase (And first letter to Upper) [Ex: AbCdEf]
  52.    ''' </summary>
  53.    Public Shared Function CamelCase_First_Upper(ByVal Text As String) As String
  54.        Return Char.ToUpper(Text(0)) & System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text).Replace(" ", "").Substring(1)
  55.    End Function
  56.  
  57.    ''' <summary>
  58.    ''' Convert to MixedCase (And first letter to Lower) [Ex: aB Cd eF]
  59.    ''' </summary>
  60.    Public Shared Function MixedCase_First_Lower(ByVal Text As String) As String
  61.        Dim MixedString As String = Nothing
  62.        For X As Integer = 0 To Text.Length - 1
  63.            Application.DoEvents()
  64.            Dim c As Char = Text(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.    End Function
  71.  
  72.    ''' <summary>
  73.    ''' Convert to MixedCase (And first letter to Upper) [Ex: Ab cD Ef]
  74.    ''' </summary>
  75.    Public Shared Function MixedCase_First_Upper(ByVal Text As String) As String
  76.        Dim MixedString As String = Nothing
  77.        For X As Integer = 0 To Text.Length - 1
  78.            Application.DoEvents()
  79.            Dim c As Char = Text(X)
  80.            If (X / 2).ToString.Contains(",") Then _
  81.                 MixedString += c.ToString.ToLower _
  82.            Else MixedString += c.ToString.ToUpper
  83.        Next
  84.        Return MixedString
  85.    End Function
  86.  
  87.    ''' <summary>
  88.    ''' Convert to MixedCase (And first letter of each word to Lower) [Ex: aB cD eF]
  89.    ''' </summary>
  90.    Public Shared Function MixedCase_Word_Lower(ByVal Text As String) As String
  91.        Dim MixedString As String = Nothing
  92.        Dim Count As Integer = 1
  93.        For X As Integer = 0 To Text.Length - 1
  94.            Application.DoEvents()
  95.            Dim c As Char = Text(X)
  96.            If Not c = " " Then Count += 1 Else Count = 1
  97.            If (Count / 2).ToString.Contains(",") Then _
  98.                 MixedString += c.ToString.ToUpper _
  99.            Else MixedString += c.ToString.ToLower
  100.        Next
  101.        Return MixedString
  102.    End Function
  103.  
  104.    ''' <summary>
  105.    ''' Convert to MixedCase (And first letter of each word to Upper) [Ex: Ab Cd Ef]
  106.    ''' </summary>
  107.    Public Shared Function MixedCase_Word_Upper(ByVal Text As String) As String
  108.        Dim MixedString As String = Nothing
  109.        Dim Count As Integer = 1
  110.        For X As Integer = 0 To Text.Length - 1
  111.            Application.DoEvents()
  112.            Dim c As Char = Text(X)
  113.            If Not c = " " Then Count += 1 Else Count = 1
  114.            If (Count / 2).ToString.Contains(",") Then _
  115.                 MixedString += c.ToString.ToLower _
  116.            Else MixedString += c.ToString.ToUpper
  117.        Next
  118.        Return MixedString
  119.    End Function
  120.  
  121.    ''' <summary>
  122.    ''' Convert to DelimitedCase (And All letters to Lower) [Ex: ab-cd-ef]
  123.    ''' </summary>
  124.    Public Shared Function DelimitedCase_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  125.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  126.        Return rgx.Replace(Text.ToLower, Delimiter)
  127.    End Function
  128.  
  129.    ''' <summary>
  130.    ''' Convert to DelimitedCase (And All letters to Upper) [Ex: AB-CD-EF]
  131.    ''' </summary>
  132.    Public Shared Function DelimitedCase_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  133.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  134.        Return rgx.Replace(Text.ToUpper, Delimiter)
  135.    End Function
  136.  
  137.    ''' <summary>
  138.    ''' Convert to DelimitedCase (And first letter to Upper) [Ex: Ab-cd-ef]
  139.    ''' </summary>
  140.    Public Shared Function DelimitedCase_Title(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  141.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  142.        Return rgx.Replace(Char.ToUpper(Text(0)) + StrConv(Text.Substring(1), VbStrConv.Lowercase), Delimiter)
  143.    End Function
  144.  
  145.    ''' <summary>
  146.    ''' Convert to DelimitedCase (And first letter of each word to Lower) [Ex: aB-cD-eF]
  147.    ''' </summary>
  148.    Public Shared Function DelimitedCase_Mixed_Word_Lower(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  149.        Dim MixedString As String = Nothing
  150.        Dim Count As Integer = 1
  151.        For X As Integer = 0 To Text.Length - 1
  152.            Application.DoEvents()
  153.            Dim c As Char = Text(X)
  154.            If Not c = " " Then Count += 1 Else Count = 1
  155.            If (Count / 2).ToString.Contains(",") Then _
  156.                 MixedString += c.ToString.ToUpper _
  157.            Else MixedString += c.ToString.ToLower
  158.        Next
  159.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  160.        Return rgx.Replace(MixedString, Delimiter)
  161.    End Function
  162.  
  163.    ''' <summary>
  164.    ''' Convert to DelimitedCase (And first letter of each word to Upper) [Ex: Ab-Cd-Ef]
  165.    ''' </summary>
  166.    Public Shared Function DelimitedCase_Mixed_Word_Upper(ByVal Text As String, Optional ByVal Delimiter As String = "-") As String
  167.        Dim rgx As New System.Text.RegularExpressions.Regex("\s+")
  168.        Return rgx.Replace(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text), Delimiter)
  169.    End Function
  170.  
  171.    ''' <summary>
  172.    ''' Covert string to InvertedCase [Ex: HeLLo -> hEllO ]
  173.    ''' </summary>
  174.    Public Shared Function InvertedCase(ByVal Text As String) As String
  175.        Dim InvertedString As String = String.Empty
  176.  
  177.        For Each character In Text
  178.            Application.DoEvents()
  179.            If Char.IsUpper(character) Then
  180.                InvertedString += character.ToString.ToLower
  181.            Else : InvertedString += character.ToString.ToUpper
  182.            End If
  183.        Next
  184.  
  185.        Return InvertedString
  186.    End Function
  187.  
  188. End Class
  189.  
  190. #End Region
9127  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 7 Mayo 2013, 19:42 pm
Mi versión modificada del "FileInfo"

Código
  1. #Region " Get File Info "
  2.  
  3.    ' [ Get File Info Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples:
  8.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name))
  9.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension))
  10.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName))
  11.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory))
  12.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.DriveLetter))
  13.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName))
  14.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortName))
  15.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.ShortPath))
  16.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Name_Length))
  17.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Extension_Length))
  18.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileName_Length))
  19.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Directory_Length))
  20.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FullName_Length))
  21.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileSize))
  22.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.FileVersion))
  23.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_Enum))
  24.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Attributes_String))
  25.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.CreationTime))
  26.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastAccessTime))
  27.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.LastModifyTime))
  28.    ' MsgBox(Get_File_Info("C:\Test.txt", FileInfo.Has_Extension))
  29.  
  30.    Public Enum FileInfo
  31.  
  32.        Name                  ' Filename without extension
  33.        Extension_With_Dot    ' File-Extension (with dot included)
  34.        Extension_Without_Dot ' File-Extension (without dot)
  35.        FileName              ' Filename.extension
  36.        Directory             ' Directory name
  37.        DriveLetter           ' Drive letter (only 1 letter)
  38.        FullName              ' Directory path + Filename
  39.  
  40.        ShortName ' DOS8.3 Filename
  41.        ShortPath ' DOS8.3 Path Name
  42.  
  43.        Name_Length                  ' Length of Filename without extension
  44.        Extension_With_Dot_Length    ' Length of File-Extension (with dot included)
  45.        Extension_Without_Dot_Length ' Length of File-Extension (without dot)
  46.        FileName_Length              ' Length of Filename.extension
  47.        Directory_Length             ' Length of Directory name
  48.        FullName_Length              ' Length of Directory path + Filename
  49.  
  50.        FileSize    ' Size in Bytes
  51.  
  52.        FileVersion ' Version for DLL or EXE files
  53.  
  54.        Attributes_Enum   ' Attributes in Integer format
  55.        Attributes_String ' Attributes in String format
  56.  
  57.        CreationTime   ' Date Creation time
  58.        LastAccessTime ' Date Last Access time
  59.        LastModifyTime ' Date Last Modify time
  60.  
  61.        Has_Extension  ' Checks if file have a file-extension.
  62.  
  63.    End Enum
  64.  
  65.    Private Function Get_File_Info(ByVal File As String, ByVal Information As FileInfo)
  66.  
  67.        Dim File_Info = My.Computer.FileSystem.GetFileInfo(File)
  68.  
  69.        Select Case Information
  70.  
  71.            Case FileInfo.Name : Return File_Info.Name.Substring(0, File_Info.Name.LastIndexOf("."))
  72.            Case FileInfo.Extension_With_Dot : Return File_Info.Extension
  73.            Case FileInfo.Extension_Without_Dot : Return File_Info.Extension.Split(".").Last
  74.            Case FileInfo.FileName : Return File_Info.Name
  75.            Case FileInfo.Directory : Return File_Info.DirectoryName
  76.            Case FileInfo.DriveLetter : Return File_Info.Directory.Root.ToString.Substring(0, 1)
  77.            Case FileInfo.FullName : Return File_Info.FullName
  78.  
  79.            Case FileInfo.ShortName : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortName
  80.            Case FileInfo.ShortPath : Return CreateObject("Scripting.FileSystemObject").GetFile(File).ShortPath
  81.  
  82.            Case FileInfo.Name_Length : Return File_Info.Name.Length
  83.            Case FileInfo.Extension_With_Dot_Length : Return File_Info.Extension.Length
  84.            Case FileInfo.Extension_Without_Dot_Length : Return File_Info.Extension.Split(".").Last.Length
  85.            Case FileInfo.FileName_Length : Return File_Info.Name.Length
  86.            Case FileInfo.Directory_Length : Return File_Info.DirectoryName.Length
  87.            Case FileInfo.FullName_Length : Return File_Info.FullName.Length
  88.  
  89.            Case FileInfo.FileSize : Return File_Info.Length
  90.  
  91.            Case FileInfo.FileVersion : Return CreateObject("Scripting.FileSystemObject").GetFileVersion(File)
  92.  
  93.            Case FileInfo.Attributes_Enum : Return File_Info.Attributes
  94.            Case FileInfo.Attributes_String : Return File_Info.Attributes.ToString
  95.  
  96.            Case FileInfo.CreationTime : Return File_Info.CreationTime
  97.            Case FileInfo.LastAccessTime : Return File_Info.LastAccessTime
  98.            Case FileInfo.LastModifyTime : Return File_Info.LastWriteTime
  99.  
  100.            Case FileInfo.Has_Extension : Return IO.Path.HasExtension(File)
  101.  
  102.            Case Else : Return Nothing
  103.  
  104.        End Select
  105.  
  106.    End Function
  107.  
  108. #End Region
9128  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 7 Mayo 2013, 19:17 pm


Una class para usar SevenZipSharp de forma sencilla para "comprimir/descomprimir/Crear un SFX/obtener información de zips" y mostrando el progreso de las operaciones.

Código
  1. #Region " SevenZipSharp Class "
  2.  
  3. ' [ SevenZipSharp Functions ]
  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. Add the "7z.sfx" and "7zCon.sfx" files to the project for SFX compression.
  11. '
  12. ' Examples :
  13. '
  14. ' --------
  15. ' Extract:
  16. ' --------
  17. ' SevenZipSharp.Extract("C:\File.7zip")                  ' Will be extracted in the same dir.
  18. ' SevenZipSharp.Extract("C:\File.7zip", "C:\Extracted\") ' Will be extracted in "C:\Extracted\".
  19. ' SevenZipSharp.Extract("C:\File.7zip", , "Password")    ' Will be extracted with the given password.
  20. '
  21. ' --------
  22. ' Compress:
  23. ' ---------
  24. ' SevenZipSharp.Compress("C:\File.txt")                          ' File will be compressed in the same dir.
  25. ' SevenZipSharp.Compress("C:\File.txt", "C:\Compressed\File.7z") ' File will be compressed in "C:\Compressed\".
  26. ' SevenZipSharp.Compress("C:\Folder\", , , , , , "Password")     ' Folder will be compressed with the given password.
  27. ' SevenZipSharp.Compress("C:\File.txt", , OutArchiveFormat.Zip, , CompressionMethod.Lzma, CompressionLevel.Ultra)
  28. '
  29. ' --------
  30. ' Compress SFX:
  31. ' -------------
  32. ' SevenZipSharp.Compress_SFX("C:\File.txt")                           ' File will be compressed in the same dir.
  33. ' SevenZipSharp.Compress_SFX("C:\File.txt", "C:\Compressed\File.exe") ' File will be compressed in "C:\Compressed\".
  34. ' SevenZipSharp.Compress_SFX("C:\Folder\", , , , , , , "Password")    ' Folder will be compressed with the given password.
  35. ' SevenZipSharp.Compress_SFX("C:\File.txt", , SevenZipSharp_SFX_Module.Console, CompressionLevel.Fast)
  36. '
  37. ' --------
  38. ' File Info:
  39. ' ----------
  40. ' MsgBox(SevenZipSharp.FileInfo("C:\Test.7z", SevenZip_Info.Format))
  41. ' For Each FileName In SevenZipSharp.FileInfo("C:\Test.zip", SevenZip_Info.Internal_Files_FileNames) : MsgBox(FileName) : Next
  42. '
  43. ' ------------
  44. ' * Progress *
  45. ' ------------
  46. ' Dim WithEvents SevenZipProgress_Timer As New Timer
  47. ' Private Sub SevenZipProgress_Timer_Tick(sender As Object, e As EventArgs) Handles SevenZipProgress_Timer.Tick
  48. '     ProgressBar1.Value = SevenZipSharp.SevenZip_Current_Progress
  49. '     If ProgressBar1.Value = 100 Then
  50. '         ' ...
  51. '     End If
  52. ' End Sub
  53.  
  54. Imports SevenZip
  55.  
  56. Public Class SevenZipSharp
  57.  
  58.    Public Shared SevenZipDLL As String = "7z.dll"
  59.    Public Shared SevenZip_Current_Progress As Short = 0
  60.  
  61. #Region " SevenZipSharp Extract "
  62.  
  63.    Public Shared Function Extract(ByVal InputFile As String, _
  64.                                           Optional ByVal OutputDir As String = Nothing, _
  65.                                           Optional ByVal Password As String = "Nothing") As Boolean
  66.        SevenZip_Current_Progress = 0
  67.  
  68.        Try
  69.            ' Set library path
  70.            SevenZipExtractor.SetLibraryPath(SevenZipDLL)
  71.  
  72.            ' Create extractor and specify the file to extract
  73.            Dim Extractor As SevenZipExtractor = New SevenZipExtractor(InputFile, Password)
  74.  
  75.            ' Specify the output path where the files will be extracted
  76.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  77.  
  78.            ' Add Progress Handler
  79.            AddHandler Extractor.Extracting, AddressOf SevenZipSharp_Extract_Progress
  80.  
  81.            ' Check for password matches
  82.            If Extractor.Check() Then
  83.                ' Start the extraction
  84.                Extractor.BeginExtractArchive(OutputDir)
  85.            Else
  86.                Return False ' Bad password
  87.            End If
  88.  
  89.            Return True ' File extracted
  90.  
  91.            Extractor.Dispose()
  92.  
  93.        Catch ex As Exception
  94.            'Return False ' File not extracted
  95.            Throw New Exception(ex.Message)
  96.        End Try
  97.  
  98.    End Function
  99.  
  100.    Private Shared Sub SevenZipSharp_Extract_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  101.        SevenZip_Current_Progress = e.PercentDone
  102.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  103.    End Sub
  104.  
  105. #End Region
  106.  
  107. #Region " SevenZipSharp Compress "
  108.  
  109.    Public Shared Function Compress(ByVal Input_DirOrFile As String, _
  110.                                       Optional ByVal OutputFileName As String = Nothing, _
  111.                                       Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
  112.                                       Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
  113.                                       Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
  114.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  115.                                       Optional ByVal VolumeSize As Long = Nothing, _
  116.                                       Optional ByVal Password As String = Nothing) As Boolean
  117.        SevenZip_Current_Progress = 0
  118.  
  119.        Try
  120.            ' Set library path
  121.            SevenZipCompressor.SetLibraryPath(SevenZipDLL)
  122.  
  123.            ' Create compressor
  124.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  125.  
  126.            ' Set compression parameters
  127.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  128.            Compressor.CompressionMethod = CompressionMethod ' Compression method
  129.            Compressor.ArchiveFormat = Format ' Compression file format
  130.            Compressor.CompressionMode = CompressionMode ' Append files to compressed file or overwrite the compressed file.
  131.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  132.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  133.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  134.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  135.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  136.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  137.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  138.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  139.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  140.  
  141.            If Not VolumeSize = Nothing Then
  142.                If Format = OutArchiveFormat.SevenZip Then Compressor.VolumeSize = VolumeSize _
  143.                Else Throw New Exception("Multi volume option is only avaliable for 7zip format")
  144.            End If
  145.  
  146.            ' Get File extension
  147.            Dim CompressedFileExtension As String = Nothing
  148.            Select Case Compressor.ArchiveFormat
  149.                Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
  150.                Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
  151.                Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
  152.                Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
  153.                Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
  154.                Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
  155.            End Select
  156.  
  157.            ' Add Progress Handler
  158.            AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  159.  
  160.            ' Removes the end slash ("\") if given for a directory
  161.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  162.  
  163.            ' Generate the OutputFileName if any is given.
  164.            If OutputFileName Is Nothing Then _
  165.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")
  166.  
  167.            ' Check if given argument is Dir or File ...then start the compression
  168.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  169.                If Not Password Is Nothing Then
  170.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  171.                Else
  172.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  173.                End If
  174.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  175.                If Not Password Is Nothing Then
  176.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  177.                Else
  178.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  179.                End If
  180.            End If
  181.  
  182.        Catch ex As Exception
  183.            'Return False ' File not compressed
  184.            Throw New Exception(ex.Message)
  185.        End Try
  186.  
  187.        Return True ' File compressed
  188.  
  189.    End Function
  190.  
  191.    Private Shared Sub SevenZipSharp_Compress_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  192.        SevenZip_Current_Progress = e.PercentDone
  193.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  194.    End Sub
  195.  
  196. #End Region
  197.  
  198. #Region " SevenZipSharp Compress SFX "
  199.  
  200.    Enum SevenZipSharp_SFX_Module
  201.        Normal
  202.        Console
  203.    End Enum
  204.  
  205.    Public Shared Function Compress_SFX(ByVal Input_DirOrFile As String, _
  206.                                       Optional ByVal OutputFileName As String = Nothing, _
  207.                                       Optional ByVal SFX_Module As SevenZipSharp_SFX_Module = SevenZipSharp_SFX_Module.Normal, _
  208.                                       Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
  209.                                       Optional ByVal Password As String = Nothing) As Boolean
  210.        SevenZip_Current_Progress = 0
  211.  
  212.        ' Create the .7z file
  213.        Try
  214.            ' Set library path
  215.            SevenZipCompressor.SetLibraryPath(SevenZipDLL)
  216.  
  217.            ' Create compressor
  218.            Dim Compressor As SevenZipCompressor = New SevenZipCompressor()
  219.  
  220.            ' Set compression parameters
  221.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  222.            Compressor.CompressionMethod = CompressionMethod.Lzma ' Compression Method
  223.            Compressor.ArchiveFormat = OutArchiveFormat.SevenZip ' Compression file format
  224.            Compressor.CompressionMode = CompressionMode.Create ' Append files to compressed file or overwrite the compressed file.
  225.            Compressor.DirectoryStructure = True ' Preserve the directory structure.
  226.            Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
  227.            Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
  228.            Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
  229.            Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
  230.            Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
  231.            Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
  232.            Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
  233.            Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance
  234.  
  235.            ' Add Progress Handler
  236.            AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress
  237.  
  238.            ' Removes the end slash ("\") if given for a directory
  239.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  240.  
  241.            ' Generate the OutputFileName if any is given.
  242.            If OutputFileName Is Nothing Then
  243.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".tmp").Replace("\\", "\")
  244.            Else
  245.                OutputFileName = OutputFileName & ".tmp"
  246.            End If
  247.  
  248.            ' Check if given argument is Dir or File ...then start the compression
  249.            If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
  250.                If Not Password Is Nothing Then
  251.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
  252.                Else
  253.                    Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
  254.                End If
  255.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
  256.                If Not Password Is Nothing Then
  257.                    Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
  258.                Else
  259.                    Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
  260.                End If
  261.            End If
  262.  
  263.            ' Create the SFX file
  264.            ' Create the SFX compressor
  265.            Dim compressorSFX As SevenZipSfx = New SevenZipSfx(SfxModule.Default)
  266.            ' Set SFX Module path
  267.            If SFX_Module = SevenZipSharp_SFX_Module.Normal Then
  268.                compressorSFX.ModuleFileName = ".\7z.sfx"
  269.            ElseIf SFX_Module = SevenZipSharp_SFX_Module.Console Then
  270.                compressorSFX.ModuleFileName = ".\7zCon.sfx"
  271.            End If
  272.            ' Start the compression
  273.            ' Generate the OutputFileName if any is given.
  274.            Dim SFXOutputFileName As String
  275.            If OutputFileName.ToLower.EndsWith(".exe.tmp") Then
  276.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4)
  277.            Else
  278.                SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) & ".exe"
  279.            End If
  280.  
  281.            compressorSFX.MakeSfx(OutputFileName, SFXOutputFileName)
  282.            ' Delete the 7z tmp file
  283.            Try : IO.File.Delete(OutputFileName) : Catch : End Try
  284.  
  285.        Catch ex As Exception
  286.            'Return False ' File not compressed
  287.            Throw New Exception(ex.Message)
  288.        End Try
  289.  
  290.        Return True ' File compressed
  291.  
  292.    End Function
  293.  
  294.    Private Shared Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs)
  295.        SevenZip_Current_Progress = e.PercentDone
  296.        ' If e.PercentDone = 100 Then SevenZip_Current_Progress = 0
  297.    End Sub
  298.  
  299. #End Region
  300.  
  301. #Region " SevenZipSharp FileInfo "
  302.  
  303.    Enum File_Info
  304.        FileName
  305.        Format
  306.        Size_In_Bytes
  307.        Internal_Files_FileNames
  308.        Total_Internal_Files
  309.    End Enum
  310.  
  311.    Public Shared Function FileInfo(ByVal InputFile As String, ByVal Info As File_Info)
  312.  
  313.        Try
  314.            ' Set library path
  315.            SevenZip.SevenZipExtractor.SetLibraryPath(SevenZipDLL)
  316.  
  317.            ' Create extractor and specify the file to extract
  318.            Dim Extractor As SevenZip.SevenZipExtractor = New SevenZip.SevenZipExtractor(InputFile)
  319.  
  320.            ' Return info
  321.            Select Case Info
  322.  
  323.                Case File_Info.FileName
  324.                    Return Extractor.FileName
  325.  
  326.                Case File_Info.Format
  327.                    Return Extractor.Format
  328.  
  329.                Case File_Info.Size_In_Bytes
  330.                    Return Extractor.PackedSize
  331.  
  332.                Case File_Info.Total_Internal_Files
  333.                    Return Extractor.FilesCount
  334.  
  335.                Case File_Info.Internal_Files_FileNames
  336.                    Dim FileList As New List(Of String)
  337.                    For Each Internal_File In Extractor.ArchiveFileData
  338.                        FileList.Add(Internal_File.FileName)
  339.                    Next
  340.                    Return FileList
  341.  
  342.                Case Else
  343.                    Return Nothing
  344.  
  345.            End Select
  346.  
  347.            Extractor.Dispose()
  348.  
  349.        Catch ex As Exception
  350.            ' Return nothing
  351.            Throw New Exception(ex.Message)
  352.        End Try
  353.  
  354.    End Function
  355.  
  356. #End Region
  357.  
  358. End Class
  359.  
  360. #End Region
  361.  







Una class para usar DotNetZip de forma sencilla para "comprimir/descomprimir/Crear un SFX" y mostrando el progreso en las operaciones.

Código
  1. #Region " DotNetZip Class "
  2.  
  3. ' [ DotNetZip Functions ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions :
  8. ' 1. Add a reference to "Ionic.Zip.dll".
  9. '
  10. ' Examples :
  11. '
  12. ' --------
  13. ' Extract:
  14. ' --------
  15. ' DotNetZip_Extract("C:\File.zip")
  16. ' DotNetZip_Extract("C:\File.zip", "C:\Folder\Test\", , "MyPassword")
  17. '
  18. ' ---------
  19. ' Compress:
  20. ' ---------
  21. ' DotNetZip_Compress("C:\File.txt")
  22. ' DotNetZip_Compress("C:\Folder")
  23. ' DotNetZip_Compress("C:\Folder", "C:\Folder\Test.zip", , CompressionLevel.BestCompression, "Password", EncryptionAlgorithm.WinZipAes256)
  24. '
  25. ' -------------
  26. ' Compress SFX:
  27. ' -------------
  28. ' DotNetZip_Compress_SFX("C:\File.txt")
  29. ' DotNetZip_Compress_SFX("C:\Folder")
  30. '
  31. ' DotNetZip_Compress_SFX( _
  32. '    "C:\File.txt", "C:\Test.exe", , CompressionLevel.BestCompression, _
  33. '    "MyPassword", EncryptionAlgorithm.WinZipAes256, , , _
  34. '    ExtractExistingFileAction.OverwriteSilently, , , , _
  35. '    System.IO.Path.GetFileName("notepad.exe") _
  36. ' )
  37. '
  38. ' ------------
  39. ' * Progress *
  40. ' ------------
  41. ' Dim WithEvents DotNetZip_Progress_Timer As New Timer
  42. ' Private Sub DotNetZip_Progress_Timer_Tick(sender As Object, e As EventArgs) Handles DotNetZip_Progress_Timer.Tick
  43. '    Label1.Text = DotNetZip.CurrentFileName
  44. '    ProgressBar1.Value = DotNetZip.DotNetZip_Current_Progress
  45. '    If ProgressBar1.Value = 100 Then
  46. '       ' ...
  47. '   End If
  48. ' End Sub
  49.  
  50. Imports Ionic.Zip
  51. Imports Ionic.Zlib
  52.  
  53. Public Class DotNetZip
  54.  
  55. #Region " DotNetZip Extract "
  56.  
  57.    Public Shared DotNetZip_Current_Progress As Short = 0
  58.    Public Shared ZipFileCount As Long = 0
  59.    Public Shared ExtractedFileCount As Long = 0
  60.    Public Shared CurrentFileName As String = String.Empty
  61.  
  62.    Public Shared Function Extract(ByVal InputFile As String, _
  63.                                       Optional ByVal OutputDir As String = Nothing, _
  64.                                       Optional ByVal Overwrite As ExtractExistingFileAction = ExtractExistingFileAction.DoNotOverwrite, _
  65.                                       Optional ByVal Password As String = "Nothing" _
  66.                                     ) As Boolean
  67.  
  68.        DotNetZip_Current_Progress = 0
  69.        ZipFileCount = 0
  70.        ExtractedFileCount = 0
  71.        CurrentFileName = String.Empty
  72.  
  73.        Try
  74.            ' Create Extractor
  75.            Dim Extractor As ZipFile = ZipFile.Read(InputFile)
  76.  
  77.            ' Set Extractor parameters
  78.            Extractor.Password = Password ' Zip Password
  79.            Extractor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  80.            Extractor.ZipErrorAction = ZipErrorAction.Throw
  81.  
  82.            ' Specify the output path where the files will be extracted
  83.            If OutputDir Is Nothing Then OutputDir = My.Computer.FileSystem.GetFileInfo(InputFile).DirectoryName
  84.  
  85.            ' Add Progress
  86.            AddHandler Extractor.ExtractProgress, AddressOf DotNetZip_Extract_Progress ' Progress Handler
  87.            For Each Entry As ZipEntry In Extractor.Entries
  88.                Application.DoEvents()
  89.                ZipFileCount += 1
  90.            Next ' Total bytes size of Zip
  91.            ZipFileCount = Extractor.Entries.Count ' Total files inside Zip
  92.  
  93.            ' Start the extraction
  94.            For Each Entry As ZipEntry In Extractor.Entries
  95.                Application.DoEvents()
  96.                Entry.Extract(OutputDir, Overwrite)
  97.            Next
  98.  
  99.            ZipFileCount = 0 : ExtractedFileCount = 0 ' Reset vars
  100.            Extractor.Dispose()
  101.            Return True ' File Extracted
  102.  
  103.        Catch ex As Exception
  104.            ' Return False ' File not extracted
  105.            MsgBox(ex.Message)
  106.            Throw New Exception(ex.Message)
  107.        End Try
  108.  
  109.    End Function
  110.  
  111.    Private Shared Sub DotNetZip_Extract_Progress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
  112.  
  113.        If e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry Then
  114.            CurrentFileName = e.CurrentEntry.FileName
  115.            ExtractedFileCount += 1
  116.            DotNetZip_Current_Progress = ((100 / ZipFileCount) * ExtractedFileCount)
  117.        ElseIf e.EventType = ZipProgressEventType.Extracting_AfterExtractEntry Then
  118.            If ExtractedFileCount = ZipFileCount Then
  119.                'MessageBox.Show("Extraction Done: " & vbNewLine & _
  120.                '                             e.ArchiveName) ' Uncompression finished
  121.            End If
  122.        End If
  123.  
  124.    End Sub
  125.  
  126. #End Region
  127.  
  128. #Region " DotNetZip Compress "
  129.  
  130.    Public Shared Function Compress(ByVal Input_DirOrFile As String, _
  131.                                      Optional ByVal OutputFileName As String = Nothing, _
  132.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  133.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  134.                                      Optional ByVal Password As String = Nothing, _
  135.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None _
  136.                                    ) As Boolean
  137.  
  138.        DotNetZip_Current_Progress = 0
  139.        ZipFileCount = 0
  140.        ExtractedFileCount = 0
  141.        CurrentFileName = String.Empty
  142.  
  143.        Try
  144.            ' Create compressor
  145.            Dim Compressor As ZipFile = New ZipFile
  146.  
  147.            ' Set compression parameters
  148.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  149.            Compressor.CompressionMethod = CompressionMethod ' Compression method
  150.            Compressor.Password = Password ' Zip Password
  151.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  152.  
  153.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then _
  154.                 Compressor.Encryption = EncryptionAlgorithm.None _
  155.            Else Compressor.Encryption = Encrypt_Password ' Encryption for Zip password.
  156.  
  157.            ' Add Progress Handler
  158.            AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_Progress
  159.  
  160.            ' Removes the end slash ("\") if is given for a directory.
  161.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  162.  
  163.            ' Generate the OutputFileName if any is given.
  164.            If OutputFileName Is Nothing Then _
  165.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".zip").Replace("\\", "\")
  166.  
  167.            ' Check if given argument is Dir or File ...then start the compression
  168.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  169.                Compressor.AddDirectory(Input_DirOrFile)
  170.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  171.                Compressor.AddFile(Input_DirOrFile)
  172.            End If
  173.  
  174.            Compressor.Save(OutputFileName)
  175.            Compressor.Dispose()
  176.  
  177.        Catch ex As Exception
  178.            ' Return False ' File not compressed
  179.            MsgBox(ex.Message)
  180.            ' Throw New Exception(ex.Message)
  181.        End Try
  182.  
  183.        Return True ' File compressed
  184.  
  185.    End Function
  186.  
  187.    Private Shared Sub DotNetZip_Compress_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  188.        Application.DoEvents()
  189.  
  190.        If e.EventType = ZipProgressEventType.Saving_Started Then
  191.        ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  192.            CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed
  193.            DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1)
  194.        ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  195.            DotNetZip_Current_Progress = 100
  196.        End If
  197.  
  198.    End Sub
  199.  
  200. #End Region
  201.  
  202. #Region " DotNetZip Compress SFX "
  203.  
  204.    Public Shared Function Compress_SFX(ByVal Input_DirOrFile As String, _
  205.                                      Optional ByVal OutputFileName As String = Nothing, _
  206.                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.None, _
  207.                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Default, _
  208.                                      Optional ByVal Password As String = Nothing, _
  209.                                      Optional ByVal Encrypt_Password As EncryptionAlgorithm = EncryptionAlgorithm.None, _
  210.                                      Optional ByVal Extraction_Directory As String = ".\", _
  211.                                      Optional ByVal Silent_Extraction As Boolean = False, _
  212.                                      Optional ByVal Overwrite_Files As ExtractExistingFileAction = ExtractExistingFileAction.InvokeExtractProgressEvent, _
  213.                                      Optional ByVal Delete_Extracted_Files_After_Extraction As Boolean = False, _
  214.                                      Optional ByVal Icon As String = Nothing, _
  215.                                      Optional ByVal Window_Title As String = Nothing, _
  216.                                      Optional ByVal Window_Style As SelfExtractorFlavor = SelfExtractorFlavor.WinFormsApplication, _
  217.                                      Optional ByVal Command_Line_Argument As String = Nothing _
  218.                                    ) As Boolean
  219.  
  220.        DotNetZip_Current_Progress = 0
  221.        ZipFileCount = 0
  222.        ExtractedFileCount = 0
  223.        CurrentFileName = String.Empty
  224.  
  225.        Try
  226.            ' Create compressor
  227.            Dim Compressor As ZipFile = New ZipFile
  228.  
  229.            ' Set compression parameters
  230.            Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
  231.            ' Compression method
  232.            Compressor.Password = Password ' Zip Password
  233.            Compressor.TempFileFolder = System.IO.Path.GetTempPath() ' Temp folder for operations
  234.  
  235.            If Password Is Nothing AndAlso Not Encrypt_Password = EncryptionAlgorithm.None Then
  236.                Compressor.Encryption = EncryptionAlgorithm.None ' No encryption because no password.
  237.                Compressor.CompressionMethod = CompressionMethod ' Set any compression method.
  238.            Else
  239.                Compressor.Encryption = Encrypt_Password ' Set Encryption for Zip password.
  240.                Compressor.CompressionMethod = CompressionMethod.Deflate ' Set deflate method to don't destroy the SFX if AES encryption.
  241.            End If
  242.  
  243.            Dim SFX_Options As New SelfExtractorSaveOptions()
  244.            SFX_Options.DefaultExtractDirectory = Extraction_Directory
  245.            SFX_Options.Quiet = Silent_Extraction
  246.            SFX_Options.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently
  247.            SFX_Options.RemoveUnpackedFilesAfterExecute = Delete_Extracted_Files_After_Extraction
  248.            SFX_Options.Flavor = Window_Style
  249.            SFX_Options.PostExtractCommandLine = Command_Line_Argument
  250.            If Not Icon Is Nothing Then SFX_Options.IconFile = Icon
  251.            If Not Window_Title Is Nothing Then SFX_Options.SfxExeWindowTitle = Window_Title
  252.  
  253.            ' Add Progress Handler
  254.            AddHandler Compressor.SaveProgress, AddressOf DotNetZip_Compress_SFX_Progress
  255.  
  256.            ' Removes the end slash ("\") if is given for a directory.
  257.            If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)
  258.  
  259.            ' Generate the OutputFileName if any is given.
  260.            If OutputFileName Is Nothing Then _
  261.                OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".exe").Replace("\\", "\")
  262.  
  263.            ' Check if given argument is Dir or File ...then start the compression
  264.            If IO.Directory.Exists(Input_DirOrFile) Then ' It's a Dir
  265.                Compressor.AddDirectory(Input_DirOrFile)
  266.            ElseIf IO.File.Exists(Input_DirOrFile) Then ' It's a File
  267.                Compressor.AddFile(Input_DirOrFile)
  268.            End If
  269.  
  270.            Compressor.SaveSelfExtractor(OutputFileName, SFX_Options)
  271.            Compressor.Dispose()
  272.  
  273.        Catch ex As Exception
  274.            'Return False ' File not compressed
  275.            Throw New Exception(ex.Message)
  276.        End Try
  277.  
  278.        Return True ' File compressed
  279.  
  280.    End Function
  281.  
  282.    Private Shared Sub DotNetZip_Compress_SFX_Progress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
  283.        Application.DoEvents()
  284.  
  285.        If e.EventType = ZipProgressEventType.Saving_Started Then
  286.        ElseIf e.EventType = ZipProgressEventType.Saving_BeforeWriteEntry Then
  287.            CurrentFileName = e.CurrentEntry.FileName ' Input filename to be compressed
  288.            DotNetZip_Current_Progress = ((100 / e.EntriesTotal) * e.EntriesSaved + 1)
  289.        ElseIf e.EventType = ZipProgressEventType.Saving_Completed Then
  290.            DotNetZip_Current_Progress = 100
  291.        End If
  292.  
  293.    End Sub
  294.  
  295. #End Region
  296.  
  297. End Class
  298.  
  299. #End Region
9129  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 7 Mayo 2013, 15:13 pm
Una class para compilar otros proyectos en tiempo de ejecución.

Código:
#Region " FrameWork Compiler "

' [ FrameWork Compiler Function ]
'
' // By Elektro H@cker
'
' Examples :
' FrameWorkCompiler.FW_Compile("C:\Projects\Project.vbj", FrameWorkCompiler.CompilerVersion.FW_3_5_x86)
' FrameWorkCompiler.FW_Compile("C:\Projects\Project.sln", FrameWorkCompiler.CompilerVersion.FW_4_0_x64)

#Region " FrameWork Compiler Class "

Public Class FrameWorkCompiler

    Shared FrameWork_Location As String = Nothing ' Directory location of selected FrameWork version

    ''' <summary>
    ''' The FrameWork compiler version.
    ''' </summary>
    Public Enum CompilerVersion
        FW_1_0_x86
        FW_1_1_x86
        FW_2_0_x86
        FW_3_0_x86
        FW_3_5_x86
        FW_4_0_x86
        FW_2_0_x64
        FW_3_0_x64
        FW_3_5_x64
        FW_4_0_x64
    End Enum

    ''' <summary>
    ''' Compile a .NET project/solution.
    ''' </summary>
    Public Shared Function FW_Compile(ByVal SolutionFile As String, ByVal FrameWorkCompiler As CompilerVersion) As Boolean

        Select Case FrameWorkCompiler
            Case CompilerVersion.FW_1_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.0.3705")
            Case CompilerVersion.FW_1_1_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v1.1.4322")
            Case CompilerVersion.FW_2_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v2.0.50727")
            Case CompilerVersion.FW_3_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.0")
            Case CompilerVersion.FW_3_5_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v3.5")
            Case CompilerVersion.FW_4_0_x86 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework\v4.0.30319")
            Case CompilerVersion.FW_2_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v2.0.50727")
            Case CompilerVersion.FW_3_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.0")
            Case CompilerVersion.FW_3_5_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v3.5")
            Case CompilerVersion.FW_4_0_x64 : FrameWork_Location = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64\v4.0.30319")
            Case Else : Return False
        End Select

        Try

            Dim FWCompiler As New Process()
            Dim FWCompiler_Info As New ProcessStartInfo()

            FWCompiler_Info.FileName = IO.Path.Combine(FrameWork_Location, "msbuild.exe")
            FWCompiler_Info.Arguments = "/nologo /noautoresponse /verbosity:quiet " & """" & SolutionFile & """"
            FWCompiler_Info.UseShellExecute = False
            FWCompiler_Info.CreateNoWindow = True
            FWCompiler_Info.WindowStyle = ProcessWindowStyle.Hidden
            FWCompiler_Info.RedirectStandardOutput = True
            FWCompiler.StartInfo = FWCompiler_Info
            FWCompiler.Start()
            FWCompiler.WaitForExit()

            ' Dim ErrorOutput As String = FWCompiler.StandardOutput.ReadToEnd()
            ' MsgBox(ErrorOutput)

            If FWCompiler.ExitCode <> 0 Then
                Return False
            Else
                Return True
            End If

        Catch ex As Exception
            ' MsgBox(ex.Message)
            Return False
        End Try

    End Function

End Class

#End Region

#End Region
9130  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 7 Mayo 2013, 15:09 pm
Los snippets que posteé hace tiempo para hacer modificaciones en el registro, los he optimizado para simplificar su uso y evitar errores de sintaxis.
PD: Ahora permite añadir datos binários.

Código
  1. #Region " Reg Create Key "
  2.  
  3.    ' [ Reg Create Key Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Reg_Create_Key("HKCU\Software\MyProgram")                        ' Creates "HKCU\Software\MyProgram"
  10.    ' Reg_Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings"
  11.  
  12.    Public Function Reg_Create_Key(ByVal RegKey As String) As Boolean
  13.  
  14.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  15.        Dim KeyPath As String = Nothing
  16.  
  17.        ' Gets the RootKey
  18.        Select Case RegKey.ToUpper.Split("\").First
  19.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  20.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  21.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  22.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  23.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  24.            Case Else : Return False
  25.        End Select
  26.  
  27.        ' Gets the KeyPath
  28.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  29.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  30.  
  31.        Try
  32.            RootKey.CreateSubKey(KeyPath)
  33.            RootKey.Close()
  34.            Return True
  35.        Catch ex As Exception
  36.            Throw New Exception(ex.Message)
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Delete Key "
  2.  
  3.    ' [ Reg Delete Key Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Delete_Key("HKLM\Software\7-zip")                ' Deletes the "7-zip" tree including subkeys
  9.    ' Reg_Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys
  10.  
  11.    Public Function Reg_Delete_Key(ByVal RegKey As String) As Boolean
  12.  
  13.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  14.        Dim KeyPath As String = Nothing
  15.  
  16.        ' Gets the RootKey
  17.        Select Case RegKey.ToUpper.Split("\").First
  18.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  19.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  20.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  21.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  22.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  23.            Case Else : Return False
  24.        End Select
  25.  
  26.        ' Gets the KeyPath
  27.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  28.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  29.  
  30.        Try
  31.            RootKey.DeleteSubKeyTree(KeyPath)
  32.            RootKey.Close()
  33.            Return True
  34.        Catch ex As Exception
  35.            ' Throw New Exception(ex.Message)
  36.            Return False
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Delete Value "
  2.  
  3.    ' [ Reg Delete Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Delete_Value("HKCU\Software\7-Zip", "Lang")               ' Deletes "Lang" Value
  9.    ' Reg_Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value
  10.  
  11.    Public Function Reg_Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean
  12.  
  13.        Dim RootKey As Microsoft.Win32.RegistryKey = Nothing
  14.        Dim KeyPath As String = Nothing
  15.  
  16.        ' Gets the RootKey
  17.        Select Case RegKey.ToUpper.Split("\").First
  18.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = Microsoft.Win32.Registry.ClassesRoot
  19.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = Microsoft.Win32.Registry.CurrentConfig
  20.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = Microsoft.Win32.Registry.CurrentUser
  21.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = Microsoft.Win32.Registry.LocalMachine
  22.            Case "HKEY_PERFORMANCE_DATA" : RootKey = Microsoft.Win32.Registry.PerformanceData
  23.            Case Else : Return False
  24.        End Select
  25.  
  26.        ' Gets the KeyPath
  27.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  28.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  29.  
  30.        Try
  31.            RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue)
  32.            RootKey.Close()
  33.            Return True
  34.        Catch ex As Exception
  35.            ' Throw New Exception(ex.Message)
  36.            Return False
  37.        End Try
  38.  
  39.    End Function
  40.  
  41. #End Region


Código
  1. #Region " Reg Set Value "
  2.  
  3.    ' [ Reg Set Value Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Reg_Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String)              ' Create/Replace "Value Name" with "Data" as string data
  9.    ' Reg_Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data
  10.  
  11.  
  12.    Public Function Reg_Set_Value(ByVal RegKey As String, _
  13.                                  ByVal RegValue As String, _
  14.                                  ByVal RegData As String, _
  15.                                  ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean
  16.  
  17.        Dim RootKey As String = Nothing
  18.        Dim KeyPath As String = Nothing
  19.  
  20.        ' Gets the RootKey
  21.        Select Case RegKey.ToUpper.Split("\").First
  22.            Case "HKCR", "HKEY_CLASSES_ROOT" : RootKey = "HKEY_CLASSES_ROOT"""
  23.            Case "HKCC", "HKEY_CURRENT_CONFIG" : RootKey = "HKEY_CURRENT_CONFIG"
  24.            Case "HKCU", "HKEY_CURRENT_USER" : RootKey = "HKEY_CURRENT_USER"
  25.            Case "HKLM", "HKEY_LOCAL_MACHINE" : RootKey = "HKEY_LOCAL_MACHINE"
  26.            Case "HKEY_PERFORMANCE_DATA" : RootKey = "HKEY_PERFORMANCE_DATA"
  27.            Case Else : Return False
  28.        End Select
  29.  
  30.        ' Gets the KeyPath
  31.        For i As Integer = 1 To RegKey.Split("\").Length - 1 : KeyPath += RegKey.Split("\")(i) & "\" : Next
  32.        KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))
  33.        KeyPath = RootKey & "\" & KeyPath
  34.  
  35.        Try
  36.            If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then
  37.                My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary)
  38.            Else
  39.                My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType)
  40.            End If
  41.            Return True
  42.        Catch ex As Exception
  43.            ' Throw New Exception(ex.Message)
  44.            Return False
  45.        End Try
  46.  
  47.    End Function
  48.  
  49. #End Region
Páginas: 1 ... 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 [913] 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines