Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#6771
Cita de: StevenKhooks en  4 Agosto 2014, 05:42 AMtengo un problema al compilar el siguiente codigo en C++ a autoit

¿Y esperas que te adivinemos el problema y el mensaje de error de compilación, o piensas tener el detalle de explicarlo?.

De todas formas no es necesario, con tu pregunta te estás respondiendo a ti mismo, C++ y AutoIt son dos lenguajes distintos.

PD: Esto me recuerda a otro mensaje que publicaste, sin detalles necesarios y sin respuesta por tu parte: http://foro.elhacker.net/net/help_gui-t416628.0.html;msg1949188#msg1949188

Saludos.
#6772
"talonary"?  :xD, menuda invención :P, supongo que intentaste traducir "talonario" al inglés, en ese caso el termino correcto es counterfoil.

Respecto a la Class, ¿podrias especificar en que necesitas ayuda?, eso no me ha quedado claro,
de todas formas si lo que buscas son que te demos consejos, entonces yo te sugiero que guardes la información a modo de base de datos (XML es un formato que me gusta, porque es legible por el humano) y la guardes en un archivo local para guardar los datos de todos los clientes, serializándolo, y acceder cuando precises (deserializando).

Te mostraría un ejemplo, pero sería en VB.NET, de todas formas en MSDN puedes encontrar ejemplos de serialización por XML como este.

Espero que te haya servido de algo,
Saludos.




EDITO:
No estoy acostumbrado a manejar C#, pero aqui tienes unas cuantas mejoras que le hice:

EDITO:
Se me olvidaba comentar que mientras la class siga igual de "simple" realmente no es necesario implementar ISerializable (ni IXmlSerializable), pero mejor tenerlo implementado de manera básica por si piensas hacerle cambios "importantes" en el futuro y lo puedas necesitar, le añadí la implementación de serialización binaria, pero como ya digo todo eso no es necesario ahora mismo, sin implementarlo puedes serializar.

Código (csharp) [Seleccionar]
#region Usings

using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Xml.Serialization;
using System.Xml;

#endregion

/// <summary>
/// Class talonary (or Counterfoil? xD).
/// This class can be serialized.
/// </summary>
[Serializable]
public class talonary : ISerializable, IXmlSerializable
{

    #region Properties

    /// <summary>
    /// Gets or sets the client name.
    /// </summary>
    /// <value>The name.</value>
    public string name
    {
        get { return this._name; }
        set { this._name = value; }
    }
    private string _name;

    /// <summary>
    /// Gets or sets the client surname.
    /// </summary>
    /// <value>The surname.</value>
    public string surname
    {
        get { return this._surname; }
        set { this._surname = value; }
    }
    private string _surname;

    /// <summary>
    /// Gets or sets the client salary.
    /// </summary>
    /// <value>The salary.</value>
    public double salary
    {
        get { return this._salary; }
        set { this._salary = value; }
    }
    private double _salary;

    /// <summary>
    /// Gets the client salary.
    /// </summary>
    /// <value>The salary.</value>
    public double discountedSalary
    {
        get
        {
            return (this._salary * 0.05D) - this._salary;
        }
    }

    #endregion

    #region Constructors

    /// <summary>
    /// Prevents a default instance of the <see cref="talonary"/> class from being created.
    /// </summary>
    private talonary() { }

    /// <summary>
    /// Initializes a new instance of the <see cref="talonary"/> class.
    /// </summary>
    /// <param name="name">Indicates the client name.</param>
    /// <param name="surname">Indicates the client surname.</param>
    /// <param name="salary">Indicates the client salary.</param>
    public talonary(string name,
                    string surname,
                    double salary)
    {

        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this._name = name;
        this._surname = surname;
        this._salary = salary;
    }

    #endregion

    #region ISerializable implementation | For Binary serialization.

    /// <summary>
    /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with the data needed to serialize the target object.
    /// </summary>
    /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> to populate with data.</param>
    /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext" />) for this serialization.</param>
    [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
     void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
        {
            throw new ArgumentNullException("info");
        }

        info.AddValue("name", this._name, typeof(string));
        info.AddValue("surname", this._surname, typeof(string));
        info.AddValue("salary", this._salary, typeof(double));
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="talonary"/> class.
    /// This constructor is used to deserialize values.
    /// </summary>
    /// <param name="info">The information.</param>
    /// <param name="context">The context.</param>
    protected talonary(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
        {
            throw new ArgumentNullException("info");
        }

        this._name = (string)info.GetValue("name", typeof(string));
        this._surname = (string)info.GetValue("surname", typeof(string));
        this._salary = (double)info.GetValue("salary", typeof(double));
    }

    #endregion

    #region "IXMLSerializable implementation" | For XML serialization.

    /// <summary>
    /// This method is reserved and should not be used.
    /// When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method,
    /// and instead, if specifying a custom schema is required, apply the <see cref="T:XmlSchemaProviderAttribute"/> to the class.
    /// </summary>
    /// <returns>
    /// An <see cref="T:Xml.Schema.XmlSchema"/> that describes the XML representation of the object
    /// that is produced by the <see cref="M:IXmlSerializable.WriteXml(Xml.XmlWriter)"/> method
    /// and consumed by the <see cref="M:IXmlSerializable.ReadXml(Xml.XmlReader)"/> method.
    /// </returns>
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    /// <summary>
    /// Converts an object into its XML representation.
    /// </summary>
    /// <param name="writer">The <see cref="T:Xml.XmlWriter"/> stream to which the object is serialized.</param>
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("name", this._name);
        writer.WriteElementString("surname", this._surname);
        writer.WriteElementString("salary", Convert.ToString(this._salary));
    }

    /// <summary>
    /// Generates an object from its XML representation.
    /// </summary>
    /// <param name="reader">The <see cref="T:Xml.XmlReader"/> stream from which the object is deserialized.</param>
    public void ReadXml(XmlReader reader)
    {
        reader.ReadStartElement(base.GetType().Name);
        this._name = reader.ReadElementContentAsString();
        this._surname = reader.ReadElementContentAsString();
        this._salary = reader.ReadElementContentAsDouble();
    }

    #endregion

}


EDITO:
No te vendría mal leer esto, sobre la serialización XML: http://support.microsoft.com/kb/316730

Ejemplo:

Código (vbnet) [Seleccionar]

   Imports System.IO
   Imports System.Xml.Serialization
   
   Public Class TestClass : Inherits form
   
      Private Sub Test_Handler() Handles MyBase.Shown
   
          Dim Clients As New List(Of talonary)
          With Clients
              .Add(New talonary("pedro", "castaño", 10.0R))
              .Add(New talonary("manolo", "ToLoko", 150.0R))
              .Add(New talonary("Elektro", "Zero", Double.MaxValue))
          End With
   
          ' Serialización XML.
          Using Writer As New StreamWriter(".\Clients.xml")
   
              Dim Serializer As New XmlSerializer(Clients.GetType)
              Serializer.Serialize(Writer, Clients)
   
          End Using
   
          ' Deserialización XML.
          Using Reader As New StreamReader(".\Clients.xml")
   
              Dim Serializer As New XmlSerializer(Clients.GetType)
              Dim tmpClients As List(Of talonary) = Serializer.Deserialize(Reader)
   
              For Each Client As talonary In tmpClients
                  MessageBox.Show(Client.name)
              Next
   
          End Using
   
      End Sub
   
   End Class


Traducción al vuelo a C# (no lo he testeado):
Código (csharp) [Seleccionar]

   using Microsoft.VisualBasic;
   using System;
   using System.Collections;
   using System.Collections.Generic;
   using System.Data;
   using System.Diagnostics;
   using System.IO;
   using System.Xml.Serialization;
   
   public class TestClass : form
   {
   
   
   private void Test_Handler()
   {
   List<talonary> Clients = new List<talonary>();
   var _with1 = Clients;
   _with1.Add(new talonary("pedro", "castaño", 10.0));
   _with1.Add(new talonary("manolo", "ToLoko", 150.0));
   _with1.Add(new talonary("Elektro", "Zero", double.MaxValue));
   
   // Serialización XML.
   using (StreamWriter Writer = new StreamWriter(".\\Clients.xml")) {
   
   XmlSerializer Serializer = new XmlSerializer(Clients.GetType);
   Serializer.Serialize(Writer, Clients);
   
   }
   
   // Deserialización XML.
   using (StreamReader Reader = new StreamReader(".\\Clients.xml")) {
   
   XmlSerializer Serializer = new XmlSerializer(Clients.GetType);
   List<talonary> tmpClients = Serializer.Deserialize(Reader);
   
   foreach (talonary Client in tmpClients) {
   MessageBox.Show(Client.name);
   }
   
   }
   
   }
   public TestClass()
   {
   Shown += Test_Handler;
   }
   
   }
   
   //=======================================================
   //Service provided by Telerik (www.telerik.com)
   //Conversion powered by NRefactory.
   //Twitter: @telerik
   //Facebook: facebook.com/telerik
   //=======================================================

   
Saludos.
#6773
Buenas

Este es un tema que se ha comentado, explicado, y solucionado CIENTOS de veces en el foro, pues no eres el único que se ha preguntado "como crackear un archivo comprimido", eso ya lo sabías, así que porfavor utiliza el buscador del foro antes de preguntar, que para algo está, jeje.

· http://foro.elhacker.net/hacking_avanzado/como_sacar_la_contrasena_de_un_archivo_winrar-t399233.0.html;msg1886728#msg1886728
· http://foro.elhacker.net/hacking_basico/como_hackear_archivos_con_metodo_fuerza_bruta-t410646.0.html;msg1927549#msg1927549
· http://foro.elhacker.net/software/iquestcomo_abrir_archivos_rar_que_tengan_contrasenas-t311203.0.html;msg1899910#msg1899910
· http://foro.elhacker.net/search.html

Lo más práctico, lógico, y sencillo es que antes de descargarte un archivo pesado compruebes si especifica alguna contraseña en la fuente (página) desde donde iniciaste la descarga.

Saludos.
#6774
Cita de: ivancea96 en  3 Agosto 2014, 17:33 PMYa van 30 páginas xD

Pues vamos a por las 300 :)

(triplicando mis espectativas xD)

Saludos!
#6775
Ejemplos de uso de la librería dnlib (de4dot): https://github.com/0xd4d/dnlib

Aunque de momento es una Class muy básica, pues dnlib es muy extenso pero con documentación muy escasa.

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

#Region " Usage Examples "

'Private Sub Test() Handles MyBase.Shown
'
'    Dim Assembly As ModuleDefMD =
'        dnlibHelper.LoadAssembly("C:\Application.exe")
'
'    Dim FrameworkVersion As String =
'        dnlibHelper.GetRuntimeVersion(Assembly)
'
'    Dim IsNativeCoded As Boolean =
'        dnlibHelper.AssemblyHasNativeCode(Assembly)
'
'    Dim Methods As List(Of MethodDef) =
'        dnlibHelper.GetMethods(Assembly, "Main") ' Searchs a Class named "Main"
'
'    For Each Method As MethodDef In Methods
'
'        ' If method contains instructions then...
'        If Method.HasBody Then
'
'            Dim sb As New System.Text.StringBuilder
'            With sb
'                .AppendLine(String.Format("Method Name: {0}", Method.Name))
'                .AppendLine()
'                .AppendLine(String.Format("Method Signature: {0}", Method.Signature.ToString))
'                .AppendLine()
'                .AppendLine(String.Format("Method Instructions: {0}", Environment.NewLine &
'                                          String.Join(Environment.NewLine, Method.Body.Instructions)))
'            End With
'
'            MessageBox.Show(sb.ToString)
'
'        End If ' method.HasBody
'
'    Next Method
'
'End Sub

#End Region

#Region " Imports "

Imports dnlib.DotNet
Imports dnlib.DotNet.Emit

#End Region

''' <summary>
''' Class dnlibHelper. This class cannot be inherited.
''' </summary>
Public NotInheritable Class dnlibHelper

   ''' <summary>
   ''' Loads an Assembly into a ModuleDefMD instance.
   ''' </summary>
   ''' <param name="Assembly">The assembly filepath.</param>
   ''' <returns>ModuleDefMD.</returns>
   Public Shared Function LoadAssembly(ByVal Assembly As String) As ModuleDefMD

       Return ModuleDefMD.Load(Assembly)

   End Function

   ''' <summary>
   ''' Determines whether a .Net Assembly has native code (C++/CLI).
   ''' </summary>
   ''' <param name="Assembly">The Assembly.</param>
   ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
   Public Shared Function AssemblyHasNativeCode(ByVal Assembly As ModuleDef) As Boolean

       If Assembly.IsILOnly Then
           ' This assembly has only IL code, and no native code (for example it's a C# or VB.NET assembly)
           Return True

       Else
           ' This assembly has native code (for example it's C++/CLI)
           Return False

       End If

   End Function

   ''' <summary>
   ''' Determines whether a .Net Assembly has native code (C++/CLI).
   ''' </summary>
   ''' <param name="Assembly">The Assembly filepath.</param>
   ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
   Public Shared Function AssemblyHasNativeCode(ByVal Assembly As String) As Boolean

       Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)

           Return AssemblyHasNativeCode(ass)

       End Using

   End Function

   ''' <summary>
   ''' Gets the .Net Framework runtime version of a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <returns>System.String.</returns>
   Public Shared Function GetRuntimeVersion(ByVal Assembly As ModuleDefMD) As String

       Return Assembly.RuntimeVersion

   End Function

   ''' <summary>
   ''' Gets the .Net Framework runtime version of a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly filepath.</param>
   ''' <returns>System.String.</returns>
   Public Shared Function GetRuntimeVersion(ByVal Assembly As String) As String

       Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
           Return GetRuntimeVersion(ass)
       End Using

   End Function

   ''' <summary>
   ''' Gets all the Types defined (including nested Types) inside a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <returns>TypeDef().</returns>
   Public Shared Function GetTypes(ByVal Assembly As ModuleDefMD) As List(Of TypeDef)

       Return Assembly.GetTypes.ToList

   End Function

   ''' <summary>
   ''' Gets all the Methods defined in a existing Type inside a .Net assembly.
   ''' </summary>
   ''' <param name="Assembly">The assembly.</param>
   ''' <param name="TypeName">Name of the type to find.</param>
   ''' <returns>MethodDef().</returns>
   Public Shared Function GetMethods(ByVal Assembly As ModuleDefMD,
                                     ByVal TypeName As String) As List(Of MethodDef)

       Dim methods As List(Of MethodDef) = Nothing

       For Each t As TypeDef In Assembly.GetTypes

           If t.HasMethods AndAlso t.Name.String.Equals(TypeName, StringComparison.OrdinalIgnoreCase) Then
               methods = t.Methods.ToList
               Exit For
           End If

       Next t

       Return methods

   End Function

End Class
#6776
Ejemplo de como usar un Proxy:

Código (vbnet) [Seleccionar]
        Dim Request As Net.HttpWebRequest = Net.HttpWebRequest.Create("http://whatismyipaddress.com/")

        With Request
            .Proxy = New Net.WebProxy(Host:="93.115.8.229", Port:=7808)
        End With

        Using StrReader As New IO.StreamReader(Request.GetResponse().GetResponseStream)

            Dim IPRegEx As New System.Text.RegularExpressions.Regex("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
            Dim IPValue As String = IPRegEx.Match(StrReader.ReadToEnd).Value

            MessageBox.Show(String.Format("Your IP Adress is: {0}", IPValue))

        End Using





Hace parpadear la ventana o el botón de la barra de tareas de un proceso

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

#Region " Usage Examples "

''Flash the Button TaskBar until the window becomes active.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.TaskBar Or WindowFlasher.FlashFlags.Until_Foreground)

''Flash the Caption and the Button TaskBar until the "Stop" flag is set.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.All Or WindowFlasher.FlashFlags.Until_Stop)

''Set the "Stop" flag, to stop flashing.
'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.Stop)

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

''' <summary>
''' Flashes a Window and/or it's button in the TaskBar.
''' </summary>
Public Class WindowFlasher

#Region " P/Invoke "

    ''' <summary>
    ''' Contains Native Windows API Methods.
    ''' </summary>
    Friend Class NativeMethods

#Region " Methods "

        ''' <summary>
        ''' Flashes the specified window.
        ''' It does not change the active state of the window.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679347%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="pwfi">A pointer to a FLASHWINFO structure.</param>
        ''' <returns>
        ''' The return value specifies the window's state before the call to the FlashWindowEx function.
        ''' If the window caption was drawn as active before the call, the return value is nonzero.
        ''' Otherwise, the return value is zero.
        ''' </returns>
        <DllImport("user32.dll")>
        Friend Shared Function FlashWindowEx(
               ByRef pwfi As FLASHWINFO
        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

#End Region

#Region " Structures "

        ''' <summary>
        ''' Contains the flash status for a window and the number of times the system should flash the window.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348%28v=vs.85%29.aspx
        ''' </summary>
        <StructLayout(LayoutKind.Sequential)>
        Friend Structure FLASHWINFO

            ''' <summary>
            ''' The size of the structure, in bytes.
            ''' </summary>
            Friend cbSize As UInteger

            ''' <summary>
            ''' A handle to the window to be flashed.
            ''' The window can be either opened or minimized.
            ''' </summary>
            Friend hwnd As IntPtr

            ''' <summary>
            ''' The flash status.
            ''' </summary>
            Friend dwFlags As FlashFlags

            ''' <summary>
            ''' The number of times to flash the window.
            ''' </summary>
            Friend uCount As UInteger

            ''' <summary>
            ''' The rate at which the window is to be flashed, in milliseconds.
            ''' If dwTimeout is zero, the function uses the default cursor blink rate.
            ''' </summary>
            Friend dwTimeout As UInteger

        End Structure

#End Region

    End Class

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Contains the flash status for a window.
    ''' </summary>
    <Description("Enum used as 'FlashFlags' parameter in 'FlashWindow' function.")>
    <Flags>
    Public Enum FlashFlags As Integer

        ''' <summary>
        ''' Stop flashing.
        ''' The system restores the window to its original state.
        ''' </summary>   
        [Stop] = 0I

        ''' <summary>
        ''' Flash the window caption.
        ''' </summary>
        Caption = 1I

        ''' <summary>
        ''' Flash the taskbar button.
        ''' </summary>
        TaskBar = 2I

        ''' <summary>
        ''' Flash both the window caption and taskbar button.
        ''' This is equivalent to setting the 'Caption Or TaskBar' flags.
        ''' </summary>
        All = 3I

        ''' <summary>
        ''' Flash continuously, until the 'Stop' flag is set.
        ''' </summary>
        Until_Stop = 4I

        ''' <summary>
        ''' Flash continuously until the window comes to the foreground.
        ''' </summary>
        Until_Foreground = 12I

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Flashes the specified window.
    ''' It does not change the active state of the window.
    ''' </summary>
    ''' <param name="Handle">
    ''' Indicates the handle to the window to flash.
    ''' </param>
    ''' <param name="FlashFlags">
    ''' Indicates the flash flags.
    ''' </param>
    ''' <param name="FlashCount">
    ''' Indicates the number of times to flash the window.
    ''' </param>
    ''' <param name="FlashDelay">
    ''' Indicates the rate at which the window is to be flashed, in milliseconds.
    ''' If dwTimeout is zero, the function uses the default cursor blink rate.
    ''' </param>
    ''' <returns>
    ''' The return value specifies the window's state before the call to the FlashWindowEx function.
    ''' If the window caption was drawn as active before the call, the return value is nonzero.
    ''' Otherwise, the return value is zero.
    ''' </returns>
    Public Shared Function Flash(ByVal [Handle] As IntPtr,
                                 ByVal FlashFlags As FlashFlags,
                                 Optional ByVal FlashCount As UInteger = UInteger.MaxValue,
                                 Optional ByVal FlashDelay As UInteger = 0UI) As Boolean

        Dim fInfo As New NativeMethods.FLASHWINFO()

        With fInfo

            .cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo))
            .hwnd = [Handle]
            .dwFlags = FlashFlags
            .uCount = FlashCount
            .dwTimeout = FlashDelay

        End With

        Return NativeMethods.FlashWindowEx(fInfo)

    End Function

#End Region

End Class
#6777
Como convertir una expresión de un valor Hexadecimal al tipo de expresión que se usa en VB.NET:

Nota: Esta es una forma más eficiente que la que posteé hace mucho tiempo.

Código (vbnet) [Seleccionar]
  ' Hex To VBHex
   ' By Elektro
   '
   ' Usage Examples:
   '
   ' MsgBox(HexToVBHex("FF4"))                        ' Result: &HFF4
   ' MsgBox(HexToVBHex("0xFF4"))                      ' Result: &HFF4
   ' Dim Value As Integer = CInt(HexToVBHex("0xFF4")) ' Result: 4084
   '
   ''' <summary>
   ''' Converts an Hexadecimal value to VisualBasic Hexadecimal syntax.
   ''' </summary>
   ''' <param name="Value">The Hexadecimal value as String.</param>
   ''' <returns>System.String.</returns>
   Public Function HexToVBHex(ByVal Value As String) As String

       If (String.IsNullOrEmpty(Value) Or String.IsNullOrWhiteSpace(Value)) Then
           Throw New ArgumentNullException(Value)
       End If

       Return String.Format("&H{0}", Value.
                                     TrimStart({"0"c, "x"c, "X"c, " "c, ControlChars.NullChar}).
                                     TrimEnd({" "c, ControlChars.NullChar}))

   End Function





Como obtener una cadena de texto aleatoria ...dado un set de caracteres, con la posibilidad de randomizar también el String-Case (upper-case/lower-case) de cada letra.

Código (vbnet) [Seleccionar]
   Dim Randomizer As New Random

   ' Get Random String
   ' // By Elektro
   '
   ' Usage Examples :
   ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10))
   ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyz", 10, RandomizeCase:=True))
   '
   ''' <summary>
   ''' Gets a random string.
   ''' </summary>
   ''' <param name="CharacterSet">Indicates the characters to randomize.</param>
   ''' <param name="StringLength">Indicates the resulting string length.</param>
   ''' <param name="RandomizeCase">If set to <c>true</c>, lower-case and upper-case are randomized.</param>
   ''' <returns>System.String.</returns>
   ''' <exception cref="System.Exception">
   ''' CharacterSet is empty.
   ''' or
   ''' String-Length must be greater than 0.
   ''' </exception>
   Private Function GetRandomString(ByVal CharacterSet As Char(),
                                    ByVal StringLength As Integer,
                                    Optional ByVal RandomizeCase As Boolean = False) As String

       Select Case CharacterSet.Count

           Case Is = 0
               Throw New Exception("CharacterSet is empty.")

           Case Is = 1
               Return New String(CharacterSet.First, Math.Abs(StringLength))

           Case Else

               Select Case StringLength

                   Case Is < 1
                       Throw New Exception("String-Length must be greater than 0.")

                   Case Else

                       Dim CharSetLength As Integer = CharacterSet.Length
                       Dim CharSB As New System.Text.StringBuilder

                       Do Until CharSB.Length = StringLength

                           If Not RandomizeCase Then
                               CharSB.Append(CharacterSet(Randomizer.Next(0, CharSetLength)))

                           Else

                               Select Case Randomizer.Next(0, 2)

                                   Case 0 ' Lower-Case
                                       CharSB.Append(Char.ToLower(CharacterSet(Randomizer.Next(0, CharSetLength))))

                                   Case 1 ' Upper-Case
                                       CharSB.Append(Char.ToUpper(CharacterSet(Randomizer.Next(0, CharSetLength))))

                               End Select

                           End If '/ Not RandomizeCase

                       Loop '/ CharSB.Length = StringLength

                       Return CharSB.ToString

               End Select '/ StringLength

       End Select '/  CharacterSet.Count

   End Function






Una expresión regular para obtener las Ipv4 de un String:

Código (vbnet) [Seleccionar]
   ' RegEx-Match IPv4
   ' By Elektro
   '
   ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
   '
   ' Usage Examples :
   ' Dim Addresses As String = "127.0.0.1 | 192.17.200.13 | 255.255.255.255 | 999.999.999.999"
   ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv4(Addresses)
   ' For Each m As System.Text.RegularExpressions.Match In Matches
   '     MessageBox.Show(m.Value)
   ' Next
   '
   ''' <summary>
   ''' Matches the IPv4 addresses contained in a String, using Regular Expressions.
   ''' </summary>
   ''' <param name="str">The string.</param>
   ''' <param name="options">The RegEx options.</param>
   ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
   Private Function RegExMatch_IPv4(ByVal str As String,
                                    Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
                                                              System.Text.RegularExpressions.RegexOptions.None
                                                              ) As System.Text.RegularExpressions.MatchCollection

       ' Match criteria:
       '
       ' ([0-255].[0-255].[0-255].[0-255])

       Dim Pattern As String =
           <a><![CDATA[((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])]]></a>.Value

       Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)

   End Function





Una expresión regular para obtener las Ipv6 de un String:

Nota: La expresión da fallos con ip's comprimidas como por ejemplo esta: fec0:fff::1
por lo demás todo bien.

Código (vbnet) [Seleccionar]
   ' RegEx-Match IPv6
   ' By Elektro
   '
   ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
   '
   ' Usage Examples :
   ' Dim Addresses As String = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329 | FEC0:FFFF:0000:0000:0000:0000:0000:1"
   ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv6(Addresses)
   ' For Each m As System.Text.RegularExpressions.Match In Matches
   '     MessageBox.Show(m.Value)
   ' Next
   '
   ''' <summary>
   ''' Matches the IPv6 addresses (full or compressed) contained in a String, using Regular Expressions.
   ''' </summary>
   ''' <param name="str">The string.</param>
   ''' <param name="options">The RegEx options.</param>
   ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
   Private Function RegExMatch_IPv6(ByVal str As String,
                                    Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
                                                              System.Text.RegularExpressions.RegexOptions.None
                                                              ) As System.Text.RegularExpressions.MatchCollection

       Dim Pattern As String =
           <a><![CDATA[(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))]]></a>.Value

       Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)

   End Function
#6778
Contiene métodos para enumerar los símbolos de una librería externa, como por ejemplo las funciones publicas, algo parecido a lo que hace la aplicación 'DLL Export Viewer': http://www.nirsoft.net/utils/dll_export_viewer.html

Nota: Como dato de interés, algo que yo también me pregunté en su momento:
         No existe ingeniería inversa posible para obtener las firmas de los métodos, los datatypes de los parámetros.

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

#Region " Usage Examples "

'Private Sub Test() Handles MyBase.Load

'    Dim dll As String = "C:\C++ lib x64.dll"
'    Dim initialized As Boolean = False
'    Dim hProcess As IntPtr = Nothing

'    Try
'        hProcess = Process.GetCurrentProcess().Handle

'        If (Symbols.SymInitialize(hProcess, Nothing, True)) Then
'            initialized = True
'        Else
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'        Dim baseOfDll As IntPtr = Symbols.SymLoadModuleEx(hProcess, IntPtr.Zero, dll,
'                                                          Nothing, 0, 0, IntPtr.Zero,
'                                                          Symbols.SymLoadModuleFlags.Module_And_Symbols)

'        If (baseOfDll = IntPtr.Zero) Then
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'        If Not Symbols.SymEnumSymbols(
'            hProcess,
'            baseOfDll,
'            "*",
'            AddressOf EnumSymProc, IntPtr.Zero
'        ) Then
'            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
'        End If

'    Catch ex As Exception
'        Debug.WriteLine(ex.Message)
'    Finally
'        If (initialized) Then
'            Symbols.SymCleanup(hProcess)
'        End If
'    End Try

'End Sub

'Friend Shared Function EnumSymProc(ByVal pSymInfo As IntPtr,
'                                   ByVal SymbolSize As UInteger,
'                                   ByVal UserContext As IntPtr) As Boolean

'    Dim Symbol As New Symbols.SYMBOL_INFO With
'        {
'            .SizeOfStruct = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Symbols.SYMBOL_INFO))
'        }

'    System.Runtime.InteropServices.Marshal.PtrToStructure(pSymInfo, Symbol)

'    Dim sb As New System.Text.StringBuilder

'    With sb

'        .AppendLine(String.Format("Address: {0}", CStr(Symbol.Address)))
'        .AppendLine(String.Format("Flags: {0}", Symbol.Flags.ToString))
'        .AppendLine(String.Format("Index: {0}", CStr(Symbol.Index)))
'        .AppendLine(String.Format("Module Base Address: {0}", CStr(Symbol.ModBase)))
'        .AppendLine(String.Format("Name: {0}", Symbol.Name))
'        .AppendLine(String.Format("Size: {0}", CStr(Symbol.Size)))
'        .AppendLine(String.Format("Tag: {0}", Symbol.Tag.ToString))

'    End With

'    Debug.WriteLine(sb.ToString)

'    Return True

'End Function

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

Public Class Symbols

#Region " P/Invoke "

#Region " Methods "

   ''' <summary>
   ''' Initializes the symbol handler for a process.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681351%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle that identifies the caller.
   ''' This value should be unique and nonzero, but need not be a process handle.
   ''' However, if you do use a process handle, be sure to use the correct handle.
   ''' If the application is a debugger, use the process handle for the process being debugged.
   ''' Do not use the handle returned by 'GetCurrentProcess' when debugging another process,
   ''' because calling functions like 'SymLoadModuleEx' can have unexpected results.
   ''' </param>
   ''' <param name="UserSearchPath">
   ''' The path, or series of paths separated by a semicolon (;), that is used to search for symbol files.
   ''' If this parameter is NULL, the library attempts to form a symbol path from the following sources:
   ''' The current working directory of the application.
   ''' The _NT_SYMBOL_PATH environment variable.
   ''' The _NT_ALTERNATE_SYMBOL_PATH environment variable.
   ''' </param>
   ''' <param name="fInvadeProcess">
   ''' If this value is TRUE, enumerates the loaded modules for the process
   ''' and effectively calls the 'SymLoadModule64' function for each module.</param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymInitialize(
              ByVal hProcess As IntPtr,
              ByVal UserSearchPath As String,
              <MarshalAs(UnmanagedType.Bool)>
              ByVal fInvadeProcess As Boolean
       ) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ''' <summary>
   ''' Deallocates all resources associated with the process handle.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680696%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">A handle to the process that was originally passed to the 'SymInitialize' function.</param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymCleanup(
              ByVal hProcess As IntPtr
       ) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   ''' <summary>
   ''' Sets the options mask.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="SymOptions"></param>
   ''' <returns>The function returns the current options mask.</returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymSetOptions(
              ByVal SymOptions As SymOptionFlags
       ) As Integer
   End Function

   ''' <summary>
   ''' Loads the symbol table for the specified module.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle to the process that was originally passed to the 'SymInitialize' function.
   ''' </param>
   ''' <param name="hFile">
   ''' The 'h fileA' handle to the file for the executable image.
   ''' This argument is used mostly by debuggers, where the debugger passes the file handle obtained from a debugging event.
   ''' A value of NULL indicates that 'hFile' is not used.
   ''' </param>
   ''' <param name="ImageName">
   ''' The name of the executable image.
   ''' This name can contain a partial path, a full path, or no path at all.
   ''' If the file cannot be located by the name provided, the symbol search path is used.
   ''' </param>
   ''' <param name="ModuleName">
   ''' A shortcut name for the module.
   ''' If the pointer value is NULL, the library creates a name using the base name of the symbol file.
   ''' </param>
   ''' <param name="BaseOfDll">
   ''' The load address of the module.
   ''' If the value is zero, the library obtains the load address from the symbol file.
   ''' The load address contained in the symbol file is not necessarily the actual load address.
   ''' Debuggers and other applications having an actual load address should use the real load address when calling this function.
   ''' If the image is a '.pdb' file, this parameter cannot be zero.
   ''' </param>
   ''' <param name="DllSize">
   ''' The size of the module, in bytes.
   ''' If the value is zero, the library obtains the size from the symbol file.
   ''' The size contained in the symbol file is not necessarily the actual size.
   ''' Debuggers and other applications having an actual size should use the real size when calling this function.
   ''' If the image is a '.pdb' file, this parameter cannot be zero.
   ''' </param>
   ''' <param name="Data">
   ''' A pointer to a 'MODLOAD_DATA' structure that represents headers other than the standard PE header.
   ''' This parameter is optional and can be NULL.
   ''' </param>
   ''' <param name="Flags">
   ''' This parameter can be one or more of the 'SymLoadModuleFlags' Enum values.
   ''' If this parameter is zero, the function loads the modules and the symbols for the module.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is the base address of the loaded module.
   ''' If the function fails, the return value is zero. To retrieve extended error information, call 'GetLastError'.
   ''' If the module is already loaded, the return value is zero and 'GetLastError' returns 'ERROR_SUCCESS'.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymLoadModuleEx(
              ByVal hProcess As IntPtr,
              ByVal hFile As IntPtr,
              ByVal ImageName As String,
              ByVal ModuleName As String,
              ByVal BaseOfDll As Long,
              ByVal DllSize As Integer,
              ByVal Data As IntPtr,
              ByVal Flags As SymLoadModuleFlags
       ) As ULong
   End Function

   ''' <summary>
   ''' Enumerates all symbols in a process.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680718%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="hProcess">
   ''' A handle to a process.
   ''' This handle must have been previously passed to the 'SymInitialize' function.
   ''' </param>
   ''' <param name="BaseOfDll">
   ''' The base address of the module.
   ''' If this value is zero and 'Mask' contains an exclamation point (!),
   ''' the function looks across modules.
   ''' If this value is zero and 'Mask' does not contain an exclamation point,
   ''' the function uses the scope established by the 'SymSetContext' function.
   ''' </param>
   ''' <param name="Mask">
   ''' A wildcard string that indicates the names of the symbols to be enumerated.
   ''' The text can optionally contain the wildcards, "*" and "?".
   ''' </param>
   ''' <param name="EnumSymbolsCallback">
   ''' A 'SymEnumSymbolsProc' callback function that receives the symbol information.
   ''' </param>
   ''' <param name="UserContext">
   ''' A user-defined value that is passed to the callback function, or NULL.
   ''' This parameter is typically used by an application to pass a pointer to a data structure
   ''' that provides context for the callback function.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is <c>true</c>.
   ''' If the function fails, the return value is <c>false</c>.
   ''' </returns>
   <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
   Friend Shared Function SymEnumSymbols(
              ByVal hProcess As IntPtr,
              ByVal BaseOfDll As ULong,
              <MarshalAs(UnmanagedType.LPWStr)>
              ByVal Mask As String,
              ByVal EnumSymbolsCallback As SymEnumSymbolsProc,
              ByVal UserContext As IntPtr
       ) As Boolean
   End Function

#End Region

#End Region

#Region " Types "

   ''' <summary>
   ''' Contains symbol information.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
   ''' </summary>
   <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
   Public Class SYMBOL_INFO

       ''' <summary>
       ''' The size of the structure, in bytes.
       ''' This member must be set to sizeof(SYMBOL_INFO).
       ''' Note that the total size of the data is the SizeOfStruct + (MaxNameLen - 1) * sizeof(TCHAR).
       ''' The reason to subtract one is that the first character in the name is accounted for in the size of the structure.
       ''' </summary>
       Public SizeOfStruct As UInteger

       ''' <summary>
       ''' A unique value that identifies the type data that describes the symbol.
       ''' This value does not persist between sessions.
       ''' </summary>
       Public TypeIndex As UInteger

       ''' <summary>
       ''' This member is reserved for system use.
       ''' </summary>
       Public Reserved1 As ULong

       ''' <summary>
       ''' This member is reserved for system use.
       ''' </summary>
       Public Reserved2 As ULong

       ''' <summary>
       ''' The unique value for the symbol.
       ''' The value associated with a symbol is not guaranteed to be the same each time you run the process.
       ''' For PDB symbols, the index value for a symbol is not generated until
       ''' the symbol is enumerated or retrieved through a search by name or address.
       ''' The index values for all CodeView and COFF symbols are generated when the symbols are loaded.
       ''' </summary>
       Public Index As UInteger

       ''' <summary>
       ''' The symbol size, in bytes.
       ''' This value is meaningful only if the module symbols are from a pdb file;
       ''' otherwise, this value is typically zero and should be ignored.
       ''' </summary>
       Public Size As UInteger

       ''' <summary>
       ''' The base address of the module that contains the symbol.
       ''' </summary>
       Public ModBase As ULong

       ''' <summary>
       ''' The symbol information.
       ''' This member can be one or more of the 'SymFlag' values.
       ''' </summary>
       Public Flags As SymFlag

       ''' <summary>
       ''' The value of a constant.
       ''' </summary>
       Public Value As ULong

       ''' <summary>
       ''' The virtual address of the start of the symbol.
       ''' </summary>
       Public Address As ULong

       ''' <summary>
       ''' The register.
       ''' </summary>
       Public Register As UInteger

       ''' <summary>
       ''' The DIA scope.
       ''' For more information, see the Debug Interface Access SDK in the Visual Studio documentation.
       ''' (This resource may not be available in some languages and countries.)
       ''' </summary>
       Public Scope As UInteger

       ''' <summary>
       ''' The PDB classification.
       ''' These values are defined in 'Dbghelp.h' in the 'SymTagEnum' enumeration type.
       ''' </summary>
       Public Tag As SymTagEnum

       ''' <summary>
       ''' The length of the name, in characters, not including the null-terminating character.
       ''' </summary>
       Public NameLen As UInteger

       ''' <summary>
       ''' The size of the Name buffer, in characters.
       ''' If this member is 0, the Name member is not used.
       ''' </summary>
       Public MaxNameLen As UInteger

       ''' <summary>
       ''' The name of the symbol.
       ''' The name can be undecorated if the 'SYMOPT_UNDNAME' option is used with the 'SymSetOptions' function.
       ''' </summary>
       <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1024I)>
       Public Name As String

   End Class

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Flags for 'SymLoadModuleEx' function.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'Flags' parameter of 'SymLoadModuleEx' function")>
   <FlagsAttribute()>
   Public Enum SymLoadModuleFlags As Integer

       ''' <summary>
       ''' Loads the module and the symbols for the module.
       ''' </summary>
       Module_And_Symbols = &H0UI

       ''' <summary>
       ''' Loads the module but not the symbols for the module.
       ''' </summary>
       Only_Module = &H4UI

       ''' <summary>
       ''' Creates a virtual module named 'ModuleName' at the address specified in 'BaseOfDll'.
       ''' To add symbols to this module, call the 'SymAddSymbol' function.
       ''' </summary>
       Virtual = &H1UI

   End Enum

   ''' <summary>
   ''' Contains symbol information.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'Flags' property of 'SYMBOL_INFO' Class")>
   <FlagsAttribute>
   Public Enum SymFlag As UInteger

       ''' <summary>
       ''' The Value member is used.
       ''' </summary>
       VALUEPRESENT = &H1UI

       ''' <summary>
       ''' The symbol is a register.
       ''' The Register member is used.
       ''' </summary>
       REGISTER = &H8UI

       ''' <summary>
       ''' Offsets are register relative.
       ''' </summary>
       REGREL = &H10UI

       ''' <summary>
       ''' Offsets are frame relative.
       ''' </summary>
       FRAMEREL = &H20UI

       ''' <summary>
       ''' The symbol is a parameter.
       ''' </summary>
       PARAMETER = &H40UI

       ''' <summary>
       ''' The symbol is a local variable.
       ''' </summary>
       LOCAL = &H80UI

       ''' <summary>
       ''' The symbol is a constant.
       ''' </summary>
       CONSTANT = &H100UI

       ''' <summary>
       ''' The symbol is from the export table.
       ''' </summary>
       EXPORT = &H200UI

       ''' <summary>
       ''' The symbol is a forwarder.
       ''' </summary>
       FORWARDER = &H400UI

       ''' <summary>
       ''' The symbol is a known function.
       ''' </summary>
       [FUNCTION] = &H800UI

       ''' <summary>
       ''' The symbol is a virtual symbol created by the 'SymAddSymbol' function.
       ''' </summary>
       VIRTUAL = &H1000UI

       ''' <summary>
       ''' The symbol is a thunk.
       ''' </summary>
       THUNK = &H2000UI

       ''' <summary>
       ''' The symbol is an offset into the TLS data area.
       ''' </summary>
       TLSREL = &H4000UI

       ''' <summary>
       ''' The symbol is a managed code slot.
       ''' </summary>
       SLOT = &H8000UI

       ''' <summary>
       ''' The symbol address is an offset relative to the beginning of the intermediate language block.
       ''' This applies to managed code only.
       ''' </summary>
       ILREL = &H10000UI

       ''' <summary>
       ''' The symbol is managed metadata.
       ''' </summary>
       METADATA = &H20000UI

       ''' <summary>
       ''' The symbol is a CLR token.
       ''' </summary>
       CLR_TOKEN = &H40000UI

   End Enum

   ''' <summary>
   ''' Specifies the type of symbol.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/bkedss5f.aspx
   ''' </summary>
   <Description("Enum used as 'Tag' property of 'SYMBOL_INFO' Class")>
   <Flags>
   Public Enum SymTagEnum As UInteger

       ''' <summary>
       ''' Indicates that the symbol has no type.
       ''' </summary>
       Null

       ''' <summary>
       ''' Indicates that the symbol is an .exe file.
       ''' There is only one SymTagExe symbol per symbol store.
       ''' It serves as the global scope and does not have a lexical parent.
       ''' </summary>
       Exe

       ''' <summary>
       ''' Indicates the compiland symbol for each compiland component of the symbol store.
       ''' For native applications, SymTagCompiland symbols correspond to the object files linked into the image.
       ''' For some kinds of Microsoft Intermediate Language (MSIL) images, there is one compiland per class.
       ''' </summary>
       Compiland

       ''' <summary>
       ''' Indicates that the symbol contains extended attributes of the compiland.
       ''' Retrieving these properties may require loading compiland symbols.
       ''' </summary>
       CompilandDetails

       ''' <summary>
       ''' Indicates that the symbol is an environment string defined for the compiland.
       ''' </summary>
       CompilandEnv

       ''' <summary>
       ''' Indicates that the symbol is a function.
       ''' </summary>
       [Function]

       ''' <summary>
       ''' Indicates that the symbol is a nested block.
       ''' </summary>
       Block

       ''' <summary>
       ''' Indicates that the symbol is data.
       ''' </summary>
       Data

       ''' <summary>
       ''' Indicates that the symbol is for a code annotation.
       ''' Children of this symbol are constant data strings (SymTagData, LocIsConstant, DataIsConstant).
       ''' Most clients ignore this symbol.
       ''' </summary>
       Annotation

       ''' <summary>
       ''' Indicates that the symbol is a label.
       ''' </summary>
       Label

       ''' <summary>
       ''' Indicates that the symbol is a public symbol. For native applications,
       ''' this symbol is the COFF external symbol encountered while linking the image.
       ''' </summary>
       PublicSymbol

       ''' <summary>
       ''' Indicates that the symbol is a user-defined type (structure, class, or union).
       ''' </summary>
       UDT

       ''' <summary>
       ''' Indicates that the symbol is an enumeration.
       ''' </summary>
       [Enum]

       ''' <summary>
       ''' Indicates that the symbol is a function signature type.
       ''' </summary>
       FunctionType

       ''' <summary>
       ''' Indicates that the symbol is a pointer type.
       ''' </summary>
       PointerType

       ''' <summary>
       ''' Indicates that the symbol is an array type.
       ''' </summary>
       ArrayType

       ''' <summary>
       ''' Indicates that the symbol is a base type.
       ''' </summary>
       BaseType

       ''' <summary>
       ''' Indicates that the symbol is a typedef, that is, an alias for another type.
       ''' </summary>
       Typedef

       ''' <summary>
       ''' Indicates that the symbol is a base class of a user-defined type.
       ''' </summary>
       BaseClass

       ''' <summary>
       ''' Indicates that the symbol is a friend of a user-defined type.
       ''' </summary>
       [Friend]

       ''' <summary>
       ''' Indicates that the symbol is a function argument.
       ''' </summary>
       FunctionArgType

       ''' <summary>
       ''' Indicates that the symbol is the end location of the function's prologue code.
       ''' </summary>
       FuncDebugStart

       ''' <summary>
       ''' Indicates that the symbol is the beginning location of the function's epilogue code.
       ''' </summary>
       FuncDebugEnd

       ''' <summary>
       ''' Indicates that the symbol is a namespace name, active in the current scope.
       ''' </summary>
       UsingNamespace

       ''' <summary>
       ''' Indicates that the symbol is a virtual table description.
       ''' </summary>
       VTableShape

       ''' <summary>
       ''' Indicates that the symbol is a virtual table pointer.
       ''' </summary>
       VTable

       ''' <summary>
       ''' Indicates that the symbol is a custom symbol and is not interpreted by DIA.
       ''' </summary>
       Custom

       ''' <summary>
       ''' Indicates that the symbol is a thunk used for sharing data between 16 and 32 bit code.
       ''' </summary>
       Thunk

       ''' <summary>
       ''' Indicates that the symbol is a custom compiler symbol.
       ''' </summary>
       CustomType

       ''' <summary>
       ''' Indicates that the symbol is in metadata.
       ''' </summary>
       ManagedType

       ''' <summary>
       ''' Indicates that the symbol is a FORTRAN multi-dimensional array.
       ''' </summary>
       Dimension

       ''' <summary>
       ''' Indicates that the symbol represents the call site.
       ''' </summary>
       CallSite

       ''' <summary>
       ''' Indicates that the symbol represents the inline site.
       ''' </summary>
       InlineSite

       ''' <summary>
       ''' Indicates that the symbol is a base interface.
       ''' </summary>
       BaseInterface

       ''' <summary>
       ''' Indicates that the symbol is a vector type.
       ''' </summary>
       VectorType

       ''' <summary>
       ''' Indicates that the symbol is a matrix type.
       ''' </summary>
       MatrixType

       ''' <summary>
       ''' Indicates that the symbol is a High Level Shader Language type.
       ''' </summary>
       HLSLType

   End Enum

   ''' <summary>
   ''' Sets the options mask.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
   ''' </summary>
   <Description("Enum used as 'SymOptions' parameter of 'SymSetOptions' function")>
   <Flags>
   Public Enum SymOptionFlags As Integer

       ''' <summary>
       ''' Enables the use of symbols that do not have an address.
       ''' By default, DbgHelp filters out symbols that do not have an address.
       ''' </summary>
       ALLOW_ZERO_ADDRESS = &H1000000

       ''' <summary>
       ''' All symbol searches are insensitive to case.
       ''' </summary>
       CASE_INSENSITIVE = &H1

       ''' <summary>
       ''' Pass debug output through OutputDebugString or the SymRegisterCallbackProc64 callback function.
       ''' </summary>
       DEBUG = &H80000000

       ''' <summary>
       ''' Symbols are not loaded until a reference is made requiring the symbols be loaded.
       ''' This is the fastest, most efficient way to use the symbol handler.
       ''' </summary>
       DEFERRED_LOADS = &H4

       ''' <summary>
       ''' Do not load an unmatched .pdb file.
       ''' Do not load export symbols if all else fails.
       ''' </summary>
       EXACT_SYMBOLS = &H400

       ''' <summary>
       ''' Do not display system dialog boxes when there is a media failure such as no media in a drive.
       ''' Instead, the failure happens silently.
       ''' </summary>
       FAIL_CRITICAL_ERRORS = &H200

       ''' <summary>
       ''' If there is both an uncompressed and a compressed file available, favor the compressed file.
       ''' This option is good for slow connections.
       ''' </summary>
       FAVOR_COMPRESSED = &H800000

       ''' <summary>
       ''' Ignore path information in the CodeView record of the image header when loading a .pdb file.
       ''' </summary>
       IGNORE_CVREC = &H80

       ''' <summary>
       ''' When debugging on 64-bit Windows, include any 32-bit modules.
       ''' </summary>
       INCLUDE_32BIT_MODULES = &H2000

       ''' <summary>
       ''' Disable checks to ensure a file (.exe, .dbg., or .pdb) is the correct file.
       ''' Instead, load the first file located.
       ''' </summary>
       LOAD_ANYTHING = &H40

       ''' <summary>
       ''' Loads line number information.
       ''' </summary>
       LOAD_LINES = &H10

       ''' <summary>
       ''' All C++ decorated symbols containing the symbol separator "::" are replaced by "__".
       ''' This option exists for debuggers that cannot handle parsing real C++ symbol names.
       ''' </summary>
       NO_CPP = &H8

       ''' <summary>
       ''' Prevents prompting for validation from the symbol server.
       ''' </summary>
       NO_PROMPTS = &H80000

       ''' <summary>
       ''' Prevents symbols from being loaded when the caller examines symbols across multiple modules.
       ''' Examine only the module whose symbols have already been loaded.
       ''' </summary>
       NO_UNQUALIFIED_LOADS = &H100

       ''' <summary>
       ''' DbgHelp will not load any symbol server other than SymSrv. SymSrv will not use the downstream store specified in _NT_SYMBOL_PATH. After this flag has been set, it cannot be cleared.
       ''' DbgHelp 6.0 and 6.1:  This flag can be cleared.
       ''' DbgHelp 5.1:  This value is not supported.
       ''' </summary>
       SECURE = &H40000

       ''' <summary>
       ''' All symbols are presented in undecorated form.
       ''' This option has no effect on global or local symbols because they are stored undecorated.
       ''' This option applies only to public symbols.
       ''' </summary>
       UNDNAME = &H2

   End Enum

#End Region

#Region " Delegates "

   ''' <summary>
   ''' An application-defined callback function used with the 'SymEnumSymbols', 'SymEnumTypes', and 'SymEnumTypesByName' functions.
   ''' </summary>
   ''' <param name="pSymInfo">
   ''' A pointer to a 'SYMBOL_INFO' structure that provides information about the symbol.
   ''' </param>
   ''' <param name="SymbolSize">
   ''' The size of the symbol, in bytes.
   ''' The size is calculated and is actually a guess.
   ''' In some cases, this value can be zero.
   ''' </param>
   ''' <param name="UserContext">
   ''' The user-defined value passed from the 'SymEnumSymbols' or 'SymEnumTypes' function, or NULL.
   ''' This parameter is typically used by an application to pass a pointer to a data structure
   ''' that provides context information for the callback function.</param>
   ''' <returns>
   ''' If the function returns <c>true</c>, the enumeration will continue.
   ''' If the function returns <c>false</c>, the enumeration will stop.
   ''' </returns>
   Friend Delegate Function SymEnumSymbolsProc(
          ByVal pSymInfo As IntPtr,
          ByVal SymbolSize As UInteger,
          ByVal UserContext As IntPtr
   ) As Boolean

#End Region

End Class
#6779
Como crear un archivo dummy (vacío) de cualquier tamaño:

Código (vbnet) [Seleccionar]
    ' Create Dummy File
    ' By Elektro
    '
    ' Usage Examples:
    ' CreateDummyFile("C:\DummyFile.tmp", 1024L ^ 3L) ' File with 1 GB size.
    '
    ''' <summary>
    ''' Creates a dummy zero-filled file.
    ''' </summary>
    ''' <param name="Filepath">Indicates the filepath.</param>
    ''' <param name="Length">Indicates the size, in Bytes.</param>
    Public Sub CreateDummyFile(ByVal Filepath As String,
                               Optional ByVal Length As Long = 0)

        Using fs As New IO.FileStream(Filepath, IO.FileMode.CreateNew)
            fs.SetLength(Length)
        End Using

    End Sub





Preserva, Restaura, o Establece las fechas de un archivo.

Nota: Esta versión tiene ciertas mejoras a la versión que publiqué en el foro, la mejora en concreto es la de poder restaurar las fechas si un archivo ha cambiado de ubicación o de nombre.

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

#Region " Usage Examples "

#Region " Example 1 "

'' Instance a test FileInfo using an unique temp file.
'Using fd As New FileDater(File:=New IO.FileInfo(IO.Path.GetTempFileName))
'
'    ' Preserve the current date-modified of the file.
'    fd.Preserve(FileDater.DateType.Modified)
'
'    ' Do some kind of operation that alters the current date-modified of the file.
'    IO.File.AppendAllText(fd.File.FullName, New String("X"c, 10I))
'
'    ' Restore the previously preserved date-modified on the TestFile.
'    fd.Restore(FileDater.DateType.Modified)

'End Using '/ fd

#End Region

#Region " Example 2 "

'' Declare a test filepath.
'Dim TestFile As String = "C:\Testfile.tmp"
'
'' Create the test file.
'If Not IO.File.Exists(TestFile) Then
'    Using fs As New IO.FileStream(TestFile, IO.FileMode.CreateNew, IO.FileAccess.ReadWrite)
'    End Using
'End If
'
'' Instance the FileDater Class.
'Using fd As New FileDater(File:=TestFile)
'
'    ' Preserve all the current dates of the TestFile.
'    fd.Preserve()
'
'    ' Print the preserved dates in the debug console.
'    Debug.WriteLine(String.Format("Preserved Creation   Date: {0}", fd.PreservedCreationDate.ToString))
'    Debug.WriteLine(String.Format("Preserved LastAccess Date: {0}", fd.PreservedLastAccessDate.ToString))
'    Debug.WriteLine(String.Format("Preserved LastModify Date: {0}", fd.PreservedLastModifyDate.ToString))
'
'    ' Copy the testfile to other location.
'    IO.File.Copy(fd.File.FullName, "C:\New Testfile.tmp", True)
'
'    ' Assign the new location in the instanced FileDater.
'    fd.SetFileLocation("C:\New Testfile.tmp")
'
'    ' Modify all the dated on the copied TestFile.
'    fd.Set(Date.Parse("01/01/2015"))
'
'    ' Restore all the previously preserved dates on the new TestFile.
'    fd.Restore()
'
'    ' Print the current testfile dates in the debug console.
'    Debug.WriteLine(String.Format("Current Creation   Date: {0}", fd.File.CreationTime.ToString))
'    Debug.WriteLine(String.Format("Current LastAccess Date: {0}", fd.File.LastAccessTime.ToString))
'    Debug.WriteLine(String.Format("Current LastModify Date: {0}", fd.File.LastWriteTime.ToString))
'
'End Using

#End Region

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.IO

#End Region

#Region " FileDater "

''' <summary>
''' Contains methods to preserve, set, and restore the dates contained on file.
''' </summary>
Public NotInheritable Class FileDater : Implements IDisposable

#Region " Objects "

    ''' <summary>
    ''' Contains the files that are already used in the constructor to prevent a duplicated instance for the same file.
    ''' </summary>
    Private Shared InstancedFiles As New List(Of FileInfo)

#End Region

#Region " Properties "

    ''' <summary>
    ''' Gets the file.
    ''' </summary>
    ''' <value>The file.</value>
    Public ReadOnly Property [File] As FileInfo
        Get
            Return Me._File
        End Get
    End Property
    Private _File As FileInfo

    ''' <summary>
    ''' Gets the type of the current preserved dates.
    ''' </summary>
    Public ReadOnly Property PreservedTypes As DateType
        Get
            Return Me._PreservedTypes
        End Get
    End Property
    Private _PreservedTypes As DateType = Nothing

    ''' <summary>
    ''' Gets the preserved creation date.
    ''' </summary>
    ''' <value>The preserved creation date.</value>
    Public ReadOnly Property PreservedCreationDate As Date
        Get
            Return Me._PreservedCreationDate
        End Get
    End Property
    Private _PreservedCreationDate As Date

    ''' <summary>
    ''' Gets the preserved last-access date.
    ''' </summary>
    ''' <value>The preserved creation date.</value>
    Public ReadOnly Property PreservedLastAccessDate As Date
        Get
            Return Me._PreservedLastAccessDate
        End Get
    End Property
    Private _PreservedLastAccessDate As Date

    ''' <summary>
    ''' Gets the preserved last-modify date.
    ''' </summary>
    ''' <value>The preserved creation date.</value>
    Public ReadOnly Property PreservedLastModifyDate As Date
        Get
            Return Me._PreservedLastModifyDate
        End Get
    End Property
    Private _PreservedLastModifyDate As Date

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Contains a FileDate flag.
    ''' </summary>
    <FlagsAttribute>
    Public Enum DateType As Integer

        ''' <summary>
        ''' The date when the file was created.
        ''' </summary>
        Created = 1I

        ''' <summary>
        ''' The date when the file was accessed by last time.
        ''' </summary>
        Accessed = 2I

        ''' <summary>
        ''' The date when the file was modified by last time.
        ''' </summary>
        Modified = 4I

    End Enum

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileDater"/> class.
    ''' </summary>
    ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param>
    ''' <exception cref="System.Exception"></exception>
    Public Sub New(ByVal [File] As FileInfo)

        If Not InstancedFiles.Contains([File]) Then
            Me._File = [File]
            InstancedFiles.Add([File])

        Else
            Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name))

        End If

    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileDater"/> class.
    ''' </summary>
    ''' <param name="File">Indicates the file.</param>
    Public Sub New(ByVal [File] As String)
        Me.New(New FileInfo([File]))
    End Sub

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

#End Region

#Region " Hidden Methods "

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

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

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

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

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Preserves the specified dates of the file to restore them later at any time.
    ''' Note: Dates can be preserved again at any time.
    ''' </summary>
    ''' <param name="DateType">Indicates the type of dates to preserve.</param>
    Public Sub Preserve(ByVal DateType As DateType)

        Me.DisposedCheck()

        ' Creation
        If DateType.HasFlag(FileDater.DateType.Created) Then
            Me._PreservedCreationDate = Me._File.CreationTime
        End If

        ' Accessed
        If DateType.HasFlag(FileDater.DateType.Accessed) Then
            Me._PreservedLastAccessDate = Me._File.LastAccessTime
        End If

        ' Modified
        If DateType.HasFlag(FileDater.DateType.Modified) Then
            Me._PreservedLastModifyDate = Me._File.LastWriteTime
        End If

        Me._PreservedTypes = DateType

    End Sub

    ''' <summary>
    ''' Preserves at once all the dates of the file to restore them later at any time.
    ''' Note: Dates can be preserved again at any time.
    ''' </summary>
    Public Sub Preserve()

        Me.DisposedCheck()

        Me._PreservedCreationDate = Me._File.CreationTime
        Me._PreservedLastAccessDate = Me._File.LastAccessTime
        Me._PreservedLastModifyDate = Me._File.LastWriteTime

        Me._PreservedTypes = DateType.Created Or DateType.Accessed Or DateType.Modified

    End Sub

    ''' <summary>
    ''' Restores the specified preserved dates on the file.
    ''' Note: Calling this method does not cause the deletion of any preserved date.
    ''' </summary>
    ''' <param name="DateType">Indicates the type of dates to restore on the file.</param>
    ''' <exception cref="System.Exception">Any date was preserved.</exception>
    Public Sub Restore(ByVal DateType As DateType)

        Me.DisposedCheck()

        ' Creation
        If DateType.HasFlag(FileDater.DateType.Created) _
        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then

            Me._File.CreationTime = Me._PreservedCreationDate

        ElseIf DateType.HasFlag(FileDater.DateType.Created) _
        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then

            Throw New Exception(String.Format("The specified date was not preserved.")) With {
                .Source = FileDater.DateType.Created.ToString
            }

        End If

        ' Accessed
        If DateType.HasFlag(FileDater.DateType.Accessed) _
        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then

            Me._File.LastAccessTime = Me._PreservedLastAccessDate

        ElseIf DateType.HasFlag(FileDater.DateType.Accessed) _
        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then

            Throw New Exception(String.Format("The specified date was not preserved.")) With {
                .Source = FileDater.DateType.Accessed.ToString
            }

        End If

        ' Modified
        If DateType.HasFlag(FileDater.DateType.Modified) _
        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then

            Me._File.LastWriteTime = Me._PreservedLastModifyDate

        ElseIf DateType.HasFlag(FileDater.DateType.Modified) _
        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then

            Throw New Exception(String.Format("The specified date was not preserved.")) With {
                .Source = FileDater.DateType.Modified.ToString
            }

        End If

    End Sub

    ''' <summary>
    ''' Restores at once all the preserved dates on the file.
    ''' Note: Calling this method does not cause the deletion of any preserved date.
    ''' </summary>
    Public Sub Restore()

        Me.DisposedCheck()

        ' Creation
        If Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
            Me._File.CreationTime = Me._PreservedCreationDate
        End If

        ' Accessed
        If Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
            Me._File.LastAccessTime = Me._PreservedLastAccessDate
        End If

        ' Modified
        If Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
            Me._File.LastWriteTime = Me._PreservedLastModifyDate
        End If

    End Sub

    ''' <summary>
    ''' Sets the specified dates on the file.
    ''' Note:
    ''' Calling this method does not cause the deletion of any preserved date.
    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
    ''' </summary>
    ''' <param name="DateType">Indicates the type of dates to set on the file.</param>
    ''' <param name="Date">Indicates the date.</param>
    Public Sub [Set](ByVal DateType As DateType, ByVal [Date] As Date)

        Me.DisposedCheck()

        ' Creation
        If DateType.HasFlag(FileDater.DateType.Created) Then
            Me._File.CreationTime = [Date]
        End If

        ' Accessed
        If DateType.HasFlag(FileDater.DateType.Accessed) Then
            Me._File.LastAccessTime = [Date]
        End If

        ' Modified
        If DateType.HasFlag(FileDater.DateType.Modified) Then
            Me._File.LastWriteTime = [Date]
        End If

    End Sub

    ''' <summary>
    ''' Sets at once all the dates on the file.
    ''' Note:
    ''' Calling this method does not cause the deletion of any preserved date.
    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
    ''' </summary>
    ''' <param name="Date">Indicates the date.</param>
    Public Sub [Set](ByVal [Date] As Date)

        Me.DisposedCheck()

        Me._File.CreationTime = [Date]
        Me._File.LastAccessTime = [Date]
        Me._File.LastWriteTime = [Date]

    End Sub

    ''' <summary>
    ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file.
    ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication.
    ''' Note: Calling this method does not cause the deletion of any preserved date.
    ''' </summary>
    ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param>
    ''' <exception cref="System.Exception"></exception>
    Public Sub SetFileLocation(ByVal [File] As FileInfo)

        If Not InstancedFiles.Contains([File]) Then
            InstancedFiles.Remove(Me._File)
            Me._File = [File]
            InstancedFiles.Add([File])

        Else
            Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name))

        End If

    End Sub

    ''' <summary>
    ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file.
    ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication.
    ''' Note: Calling this method does not cause the deletion of any preserved date.
    ''' </summary>
    ''' <param name="File">Indicates the file.</param>
    ''' <exception cref="System.Exception"></exception>
    Public Sub SetFileLocation(ByVal [File] As String)

        Me.SetFileLocation(New FileInfo([File]))

    End Sub

#End Region

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private IsDisposed As Boolean = False

    ''' <summary>
    ''' Prevent calls to methods after disposing.
    ''' </summary>
    ''' <exception cref="System.ObjectDisposedException"></exception>
    Private Sub DisposedCheck()

        If Me.IsDisposed Then
            Throw New ObjectDisposedException(Me.GetType().FullName)
        End If

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ''' <summary>
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' <param name="IsDisposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal IsDisposing As Boolean)

        If Not Me.IsDisposed Then

            If IsDisposing Then
                InstancedFiles.Remove(Me._File)
            End If

        End If

        Me.IsDisposed = True

    End Sub

#End Region

End Class

#End Region
#6780
Ejemplo detallado de como parsear la salida estándar y la salida de error de un proceso, de forma asíncrona.

Código (vbnet) [Seleccionar]
    ' Usage Examples:
    ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".exe"))
    ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".xXx"))

    ''' <summary>
    ''' The Process Object.
    ''' </summary>
    Private WithEvents MyProcess As Process =
        New Process With {.StartInfo =
            New ProcessStartInfo With {
                .CreateNoWindow = True,
                .UseShellExecute = False,
                .RedirectStandardError = True,
                .RedirectStandardOutput = True
           }
        }

    ''' <summary>
    ''' Indicates the string to search.
    ''' </summary>
    Private Find As String = String.Empty

    ''' <summary>
    ''' Determines whether a result is found.
    ''' </summary>
    Private ResultFound As Boolean = False

    ''' <summary>
    ''' Runs a command on the CMD.
    ''' </summary>
    ''' <param name="Command">Indicates the Command to run.</param>
    ''' <param name="Find">Indicates a string to find in the Output.</param>
    ''' <returns><c>true</c> if the specified string is found, <c>false</c> otherwise.</returns>
    Public Function RunCommand(ByVal Command As String,
                               ByVal Find As String) As Boolean

        Me.Find = Find
        Me.ResultFound = False

        With MyProcess

            AddHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived
            AddHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived

            .StartInfo.FileName = "CMD.exe"
            .StartInfo.Arguments = "/C " & ControlChars.Quote & Command & ControlChars.Quote

            .Start()
            .BeginOutputReadLine()
            .BeginErrorReadLine()
            .WaitForExit()

            RemoveHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived
            RemoveHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived

        End With

        Return Me.ResultFound

    End Function

    ''' <summary>
    ''' Handles the 'OutputDataReceived' of the 'RunCommand' method.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
    Private Sub RunCommand_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)

        If e.Data Is Nothing OrElse Me.ResultFound Then

            With MyProcess

                .CancelOutputRead()

                If Not .HasExited Then
                    Try
                        .Kill()
                        Debug.WriteLine("Process killed successfully!")
                    Catch ex As Exception
                        Debug.WriteLine(ex.Message)
                    End Try
                End If

            End With

        ElseIf e.Data.ToLower.Contains(Me.Find.ToLower) Then
            Me.ResultFound = True
            Debug.WriteLine("StdOut: " & e.Data)
            Debug.WriteLine("Result Found!")
            Debug.WriteLine("Stopping CMD execution at this point...")

        Else
            Debug.WriteLine("StdOut: " & e.Data)

        End If

    End Sub

    ''' <summary>
    ''' Handles the 'ErrorDataReceived' of the 'RunCommand' method.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
    Private Sub RunCommand_ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)

        If e.Data Is Nothing OrElse Me.ResultFound Then

            With MyProcess

                .CancelErrorRead()

                If Not .HasExited Then
                    Try
                        .Kill()
                        Debug.WriteLine("Process killed successfully!")
                    Catch ex As Exception
                        Debug.WriteLine(ex.Message)
                    End Try
                End If

            End With

        Else
            Debug.WriteLine("StdErr: " & e.Data)

        End If

    End Sub





Un ayudante del proceso MKVMerge (de MKVToolnix)

No le aádí casi funcionalidades, solamente las que necesité usar:

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

#Region " Usage Examples "

'Using MKVMerge As New MKVMergeHelper

'    MessageBox.Show(MKVMerge.Version)
'    MessageBox.Show(MKVMerge.ContainsTrackType("File.mkv", MKVMergeHelper.TrackType.Subtitle))

'End Using

#End Region

Public Class MKVMergeHelper : Implements IDisposable

#Region " Properties "

    ''' <summary>
    ''' Gets or sets the mkvmerge.exe file location.
    ''' </summary>
    ''' <value>The MKVmerge.exe file location.</value>
    Public Property MKVMergeLocation As String = ".\mkvmerge.exe"

    ''' <summary>
    ''' Gets the MKVMerge.exe version.
    ''' </summary>
    ''' <value>The MKVMerge.exe version.</value>
    Public ReadOnly Property Version As String
        Get
            Me.GetVersion()
            Return Me._Version
        End Get
    End Property
    Private _Version As String = String.Empty

#End Region

#Region " Other Objects "

    ''' <summary>
    ''' The MKVMerge Process Object.
    ''' </summary>
    Private WithEvents procMKVMerge As Process =
        New Process With {.StartInfo =
            New ProcessStartInfo With {
                .CreateNoWindow = True,
                .UseShellExecute = False,
                .RedirectStandardError = True,
                .RedirectStandardOutput = True
           }
        }

    ''' <summary>
    ''' Determines whether a file contains the specified track type.
    ''' </summary>
    Private TrackTypeFound As Boolean = False

    ''' <summary>
    ''' Indicates the current tracktype to search.
    ''' </summary>
    Private CurrentTrackType As TrackType = Nothing

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Specifies a type of track.
    ''' </summary>
    Public Enum TrackType As Integer

        ''' <summary>
        ''' Video track.
        ''' </summary>
        Video = 0

        ''' <summary>
        ''' Audio track.
        ''' </summary>
        Audio = 1

        ''' <summary>
        ''' Subtitle.
        ''' </summary>
        Subtitle = 2

        ''' <summary>
        ''' Attachment.
        ''' </summary>
        Attachment = 3

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Determines whether mkvmerge.exe file exist.
    ''' </summary>
    ''' <returns><c>true</c> if mkvmerge.exe file exist; otherwise, <c>false</c>.</returns>
    Public Function IsAvaliable() As Boolean

        Return IO.File.Exists(Me.MKVMergeLocation)

    End Function

    ''' <summary>
    ''' Determines whether a file contains the specified track type.
    ''' </summary>
    ''' <param name="file">Indicates the file.</param>
    ''' <param name="TrackType">Indicates the type of the track.</param>
    ''' <returns><c>true</c> if the specified track type is found, <c>false</c> otherwise.</returns>
    Public Function ContainsTrackType(ByVal file As String, ByVal TrackType As TrackType) As Boolean

        Me.CurrentTrackType = TrackType
        Me.TrackTypeFound = False

        With procMKVMerge

            AddHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived

            .StartInfo.FileName = Me.MKVMergeLocation
            .StartInfo.Arguments = String.Format("--identify ""{0}""", file)

            .Start()
            .BeginOutputReadLine()
            .WaitForExit()

            RemoveHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived

        End With

        Return Me.TrackTypeFound

    End Function

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Gets the MKVMerge.exe file version.
    ''' </summary>
    ''' <returns>The MKVMerge.exe file version.</returns>
    Private Function GetVersion() As String

        Me._Version = String.Empty

        With procMKVMerge

            AddHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived

            .StartInfo.FileName = Me.MKVMergeLocation
            .StartInfo.Arguments = String.Format("--version")

            .Start()
            .BeginOutputReadLine()
            .WaitForExit()

            RemoveHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived

        End With

        Return Me.TrackTypeFound

    End Function

#End Region

#Region " Event Handlers "

    ''' <summary>
    ''' Handles the OutputDataReceived of the ContainsTrackType method.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
    ''' <exception cref="System.Exception"></exception>
    Private Sub ContainsTrackType_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)

        If e.Data Is Nothing OrElse Me.TrackTypeFound Then
            With procMKVMerge
                .CancelOutputRead()
                If Not .HasExited Then
                    Try
                        .Kill()
                    Catch
                    End Try
                End If
            End With

        ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then
            Throw New Exception(e.Data)

        ElseIf Me.CurrentTrackType = TrackType.Video _
        AndAlso e.Data.ToLower Like "track id #*: video*" Then
            Me.TrackTypeFound = True

        ElseIf Me.CurrentTrackType = TrackType.Audio _
        AndAlso e.Data.ToLower Like "track id #*: audio*" Then
            Me.TrackTypeFound = True

        ElseIf Me.CurrentTrackType = TrackType.Subtitle _
        AndAlso e.Data.ToLower Like "track id #*: subtitle*" Then
            Me.TrackTypeFound = True

        ElseIf Me.CurrentTrackType = TrackType.Attachment _
        AndAlso e.Data.ToLower Like "attachment id*" Then
            Me.TrackTypeFound = True

        End If

    End Sub

    ''' <summary>
    ''' Handles the OutputDataReceived of the GetVersion method.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
    ''' <exception cref="System.Exception"></exception>
    Private Sub GetVersion_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)

        If e.Data Is Nothing OrElse Not String.IsNullOrEmpty(Me._Version) Then
            With procMKVMerge
                .CancelOutputRead()
                If Not .HasExited Then
                    Try
                        .Kill()
                    Catch
                    End Try
                End If
            End With

        ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then
            Throw New Exception(e.Data)

        ElseIf e.Data.ToLower Like "mkvmerge v#.*" Then
            Me._Version = e.Data.Split()(1).Substring(1)

        End If

    End Sub

#End Region

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private IsDisposed As Boolean = False

    ''' <summary>
    ''' Prevents calls to methods after disposing.
    ''' </summary>
    Private Sub DisposedCheck()
        If Me.IsDisposed Then
            Throw New ObjectDisposedException(Me.GetType().FullName)
        End If
    End Sub

    ''' <summary>
    ''' Disposes the objects generated by this instance.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ' IDisposable
    Protected Overridable Sub Dispose(IsDisposing As Boolean)

        If Not Me.IsDisposed Then

            If IsDisposing Then
                procMKVMerge.Dispose()
            End If

        End If

        Me.IsDisposed = True

    End Sub

#End Region

End Class





¿Como prevenir la instancia de una Class si ya tienes otra Class instanciada a la que le pasaste el mismo parámetro a su constructor?, pues de esta manera:

Código (vbnet) [Seleccionar]
#Region " Example Usage "

'Private Sub Test() Handles MyBase.Shown
'
'    Dim MyObject As Byte = 0
'
'    Using TestObj1 As New TestClass(MyObject)
'
'        Try
'            Dim TestObj2 As New TestClass(MyObject)
'
'        Catch ex As Exception
'            MessageBox.Show(ex.Message)
'
'        End Try
'
'    End Using
'
'End Sub

#End Region

#Region " TestClass "

Public Class TestClass : Implements IDisposable

    Private Shared InstancedObjects As New List(Of Object)
    Private _MyObject As Object

    Public Sub New(ByVal Parameter As Object)

        If Not InstancedObjects.Contains(Parameter) Then

            Me._MyObject = Parameter
            InstancedObjects.Add(Parameter)

        Else

            Throw New Exception(String.Format("Another open instance of the '{0}' class is using the same '{1}' object.",
                                              MyBase.GetType.Name, Parameter.GetType.Name))

        End If

    End Sub

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private IsDisposed As Boolean = False

    ''' <summary>
    ''' Prevent calls to methods after disposing.
    ''' </summary>
    ''' <exception cref="System.ObjectDisposedException"></exception>
    Private Sub DisposedCheck()

        If Me.IsDisposed Then
            Throw New ObjectDisposedException(Me.GetType.FullName)
        End If

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Me.Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ''' <summary>
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' <param name="IsDisposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal IsDisposing As Boolean)

        If Not Me.IsDisposed Then

            If IsDisposing Then
                InstancedObjects.Remove(Me._MyObject)
            End If

        End If

        Me.IsDisposed = True

    End Sub

#End Region

End Class

#End Region