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

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  como puedo modificar un archivo Host desde un programa ?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: como puedo modificar un archivo Host desde un programa ?  (Leído 3,312 veces)
luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
como puedo modificar un archivo Host desde un programa ?
« en: 10 Agosto 2014, 21:35 pm »

Tengo un pequeño problema cada ves que quiero modificar este archivo y es que tengo que ir a windos sisten eceteraaaaaa... abrir el archivo con el blog de notas escribir cerrar y guardar,

el archivo host sirve para bloquear las paginas que quieras pero trate de hacerlo con los métodos tradicionales pero no me sale la idea es hacer un form un texbox donde escribo la pagina a bloquear

Ojo no quiero me lo hagan solo una orientación de que método puedo usar :) o por donde irían los tiros

luis



En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
xustyx

Desconectado Desconectado

Mensajes: 213


Ver Perfil
Re: como puedo modificar un archivo Host desde un programa ?
« Respuesta #1 en: 10 Agosto 2014, 21:56 pm »

Por que no te instalas notepad++  y dejas el archivo abierto?


En línea

luis456


Desconectado Desconectado

Mensajes: 548



Ver Perfil
Re: como puedo modificar un archivo Host desde un programa ?
« Respuesta #2 en: 10 Agosto 2014, 23:01 pm »

Por que no te instalas notepad++  y dejas el archivo abierto?


Hola y gracias

pero ya lo resolví cree un icono en el escritorio con la ruta y listo ahora cada ves que lo quiero modificar lo llamo desde ese icono lo modifico y listo

tema cerrado

Luis
En línea

Que tu sabiduria no sea motivo de Humillacion para los demas
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: como puedo modificar un archivo Host desde un programa ?
« Respuesta #3 en: 11 Agosto 2014, 18:17 pm »

Te dejo aquí un regalito, esto lo escribí hoy, es la base con todos los métodos que puedas llegar a necesitar (añadir un mapeo, eliminarlo, desactivarlo, etc...),
la creación y el diseño de la interfaz gráfica sería cosa tuya, solo tendrías que instanciar esta Class y hacer que los elementos de la interfaz interactuasen con los métodos de éste.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-11-2014
  4. ' ***********************************************************************
  5. ' <copyright file="HostsFile.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class HostsFileTestClass
  13. '
  14. '    Private Sub HostsFileTestHandler() Handles MyBase.Shown
  15. '
  16. '        ' Instance the HostsFile Class.
  17. '        Dim Hosts As New HostsFile()
  18. '
  19. '        ' Set a new mapping.
  20. '        Dim Mapping As New HostsFile.MappingInfo
  21. '        With Mapping
  22. '            .HostName = "cuantodanio.es"
  23. '            .IP = Hosts.LOCALHOST ' "127.0.0.1"
  24. '            .Comment = "Test mapping comment."
  25. '        End With
  26. '
  27. '        With Hosts
  28. '
  29. '            ' Delete the Host file.
  30. '            If .FileExists Then
  31. '                .FileDelete()
  32. '            End If
  33. '
  34. '            ' Create a new one Hosts file.
  35. '            .FileCreate()
  36. '
  37. '            ' Add some new mappings.
  38. '            .Add(Mapping)
  39. '            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
  40. '
  41. '            ' Check if a mapping exists.
  42. '            If .IsMapped(Mapping) Then
  43. '                ' Disable the mapping.
  44. '                .Disable(Mapping)
  45. '            End If
  46. '
  47. '            ' Check if an existint mapping is disabled.
  48. '            If .IsDisabled("www.youtube.com") Then
  49. '                ' Remove the mapping.
  50. '                .Remove("www.youtube.com")
  51. '            End If
  52. '
  53. '            ' Open the HOSTS file with the specified text-editor.
  54. '            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
  55. '
  56. '        End With
  57. '
  58. '        ' Get the IP of a mapped Hostname.
  59. '        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
  60. '
  61. '        ' Get all the hostname mappings
  62. '        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
  63. '        For Each MappingInfo As HostsFile.MappingInfo In Mappings
  64. '
  65. '            Dim sb As New System.Text.StringBuilder
  66. '            With sb
  67. '                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
  68. '                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
  69. '                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
  70. '                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
  71. '            End With
  72. '
  73. '            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
  74. '
  75. '        Next MappingInfo
  76. '
  77. '        ' Get all the hostname mappings that matches an ip address
  78. '        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
  79. '
  80. '    End Sub
  81. '
  82. 'End Class
  83.  
  84. #End Region
  85.  
  86. #Region " Imports "
  87.  
  88. Imports System.IO
  89. Imports System.Net
  90. Imports System.Text
  91. 'Imports System.Text.RegularExpressions
  92.  
  93. #End Region
  94.  
  95. #Region " Hosts File "
  96.  
  97. ''' <summary>
  98. ''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
  99. ''' </summary>
  100. Public Class HostsFile
  101.  
  102. #Region " Constructors "
  103.  
  104.    ''' <summary>
  105.    ''' Initializes a new instance of the <see cref="HostsFile"/> class.
  106.    ''' </summary>
  107.    ''' <param name="HOSTSLocation">
  108.    ''' Optionaly indicates a custom Hosts file location.
  109.    ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
  110.    ''' </param>
  111.    Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)
  112.  
  113.        If Not String.IsNullOrEmpty(HOSTSLocation) Then
  114.            Me._HOSTSLocation = HOSTSLocation
  115.        End If
  116.  
  117.    End Sub
  118.  
  119.    ''' <summary>
  120.    ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
  121.    ''' </summary>
  122.    Private Sub New()
  123.    End Sub
  124.  
  125. #End Region
  126.  
  127. #Region " Properties "
  128.  
  129.    ''' <summary>
  130.    ''' The Hosts file location.
  131.    ''' </summary>
  132.    ''' <value>The Hosts file location.</value>
  133.    Public ReadOnly Property HOSTSLocation As String
  134.        Get
  135.            Return _HOSTSLocation
  136.        End Get
  137.    End Property
  138.    Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
  139.    Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")
  140.  
  141.    ''' <summary>
  142.    ''' The Hosts file encoding.
  143.    ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
  144.    ''' otherwise the entries will be ignored by Windows.
  145.    ''' </summary>
  146.    ''' <value>The Hosts file encoding.</value>
  147.    Public Property HOSTSEncoding As Encoding
  148.        Get
  149.            Return _HOSTSEncoding
  150.        End Get
  151.        Set(ByVal value As Encoding)
  152.            Me._HOSTSEncoding = value
  153.        End Set
  154.    End Property
  155.    Private _HOSTSEncoding As Encoding = Encoding.Default
  156.  
  157.    ''' <summary>
  158.    ''' Gets or sets the default 'LocalHost' IP address.
  159.    ''' In most computers the default address is '127.0.0.1'.
  160.    ''' </summary>
  161.    ''' <value>The default LocalHost.</value>
  162.    Public Property LOCALHOST As String
  163.        Get
  164.            Return Me._LOCALHOST
  165.        End Get
  166.        Set(ByVal value As String)
  167.            Me._LOCALHOST = value
  168.        End Set
  169.    End Property
  170.    Private _LOCALHOST As String = "127.0.0.1"
  171.  
  172.    ''' <summary>
  173.    ''' Gets the default Hosts file header.
  174.    ''' </summary>
  175.    Private ReadOnly HostsHeader As String =
  176. <a><![CDATA[
  177. # Copyright (c) 1993-2009 Microsoft Corp.
  178. #
  179. # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
  180. #
  181. # This file contains the mappings of IP addresses to host names. Each
  182. # entry should be kept on an individual line. The IP address should
  183. # be placed in the first column followed by the corresponding host name.
  184. # The IP address and the host name should be separated by at least one
  185. # space.
  186. ]]></a>.Value
  187.  
  188. #End Region
  189.  
  190. #Region " Types "
  191.  
  192. #Region " MappingInfo "
  193.  
  194.    ''' <summary>
  195.    ''' Specifies info of a HOSTS file mapping.
  196.    ''' </summary>
  197.    Public Class MappingInfo
  198.  
  199.        ''' <summary>
  200.        ''' Gets or sets the hostname.
  201.        ''' </summary>
  202.        ''' <value>The hostname.</value>
  203.        Public Property HostName As String
  204.  
  205.        ''' <summary>
  206.        ''' Gets or sets the IP address.
  207.        ''' </summary>
  208.        ''' <value>The IP address.</value>
  209.        Public Property IP As String
  210.  
  211.        ''' <summary>
  212.        ''' Gets or sets the mapping comment.
  213.        ''' </summary>
  214.        ''' <value>The mapping comment.</value>
  215.        Public Property Comment As String
  216.  
  217.        ''' <summary>
  218.        ''' This value is reserved.
  219.        ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
  220.        ''' </summary>
  221.        ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
  222.        Public Property IsDisabled As Boolean
  223.  
  224.    End Class
  225.  
  226. #End Region
  227.  
  228. #End Region
  229.  
  230. #Region " Public Methods "
  231.  
  232.    ''' <summary>
  233.    ''' Adds a new mapping.
  234.    ''' </summary>
  235.    ''' <param name="HostName">Indicates the Hostname.</param>
  236.    ''' <param name="IP">Indicates the IP address.</param>
  237.    ''' <param name="Comment">Indicates a comment for this mapping.</param>
  238.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  239.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  240.    ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
  241.    Public Sub Add(ByVal HostName As String,
  242.                   ByVal IP As String,
  243.                   Optional ByVal Comment As String = Nothing)
  244.  
  245.        If Not Me.FileExists() Then ' Hosts file does not exists.
  246.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  247.  
  248.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  249.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  250.  
  251.        ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
  252.            Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))
  253.  
  254.        Else ' Add the entry.
  255.  
  256.            ' Fix value spacing.
  257.            Dim EntryFormat As String =
  258.                IP & HostName.Insert(0I, ControlChars.Tab) &
  259.                If(Not String.IsNullOrEmpty(Comment),
  260.                   Comment.Insert(0I, ControlChars.Tab & "#"c),
  261.                   String.Empty)
  262.  
  263.            ' Write the mapping.
  264.            File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)
  265.  
  266.        End If
  267.  
  268.    End Sub
  269.  
  270.    ''' <summary>
  271.    ''' Adds a new mapping.
  272.    ''' </summary>
  273.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  274.    Public Sub Add(ByVal MappingInfo As MappingInfo)
  275.  
  276.        Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)
  277.  
  278.    End Sub
  279.  
  280.    ''' <summary>
  281.    ''' Disables an existing mapping.
  282.    ''' </summary>
  283.    ''' <param name="HostName">Indicates the Hostname.</param>
  284.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  285.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  286.    ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
  287.    Public Sub Disable(ByVal HostName As String)
  288.  
  289.        If Not Me.FileExists() Then ' Hosts file does not exists.
  290.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  291.  
  292.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  293.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  294.  
  295.        ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
  296.            Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))
  297.  
  298.        Else ' Disable the mapping.
  299.  
  300.            ' Retrieve the HOSTS file content.
  301.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  302.  
  303.            ' Iterate the mappings.
  304.            For X As Integer = 0I To (Hosts.Count - 1I)
  305.  
  306.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  307.  
  308.                    ' Retrieve the HostName of this mapping.
  309.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  310.  
  311.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  312.  
  313.                        ' Disable the mapping.
  314.                        Hosts(X) = Hosts(X).Insert(0I, "#"c)
  315.                        Exit For
  316.  
  317.                    End If ' Host.Equals(...)
  318.  
  319.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  320.  
  321.            Next X
  322.  
  323.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  324.  
  325.        End If
  326.  
  327.    End Sub
  328.  
  329.    ''' <summary>
  330.    ''' Disables an existing mapping.
  331.    ''' </summary>
  332.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  333.    Public Sub Disable(ByVal MappingInfo As MappingInfo)
  334.  
  335.        Me.Disable(MappingInfo.HostName)
  336.  
  337.    End Sub
  338.  
  339.    ''' <summary>
  340.    ''' Removes a mapping.
  341.    ''' </summary>
  342.    ''' <param name="HostName">Indicates the Hostname.</param>
  343.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  344.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  345.    Public Sub Remove(ByVal HostName As String)
  346.  
  347.        If Not Me.FileExists() Then ' Hosts file does not exists.
  348.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  349.  
  350.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  351.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  352.  
  353.        Else ' Remove the mapping.
  354.  
  355.            ' Retrieve the HOSTS file content.
  356.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  357.  
  358.            ' Iterate the mappings.
  359.            For X As Integer = 0I To (Hosts.Count - 1I)
  360.  
  361.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  362.  
  363.                    ' Retrieve the HostName of this mapping.
  364.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  365.  
  366.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  367.  
  368.                        ' Remove the mapping.
  369.                        Hosts.RemoveAt(X)
  370.                        Exit For
  371.  
  372.                    End If ' Host.Equals(...)
  373.  
  374.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  375.  
  376.            Next X
  377.  
  378.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  379.  
  380.        End If
  381.  
  382.    End Sub
  383.  
  384.    ''' <summary>
  385.    ''' Removes a mapping.
  386.    ''' </summary>
  387.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  388.    Public Sub Remove(ByVal MappingInfo As MappingInfo)
  389.  
  390.        Me.Remove(MappingInfo.HostName)
  391.  
  392.    End Sub
  393.  
  394.    ''' <summary>
  395.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
  396.    ''' </summary>
  397.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  398.    Public Function GetMappings() As List(Of MappingInfo)
  399.  
  400.        If Not Me.FileExists() Then ' Hosts file does not exists.
  401.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  402.  
  403.        Else ' Get the mapping.
  404.  
  405.            ' Retrieve the HOSTS file content.
  406.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  407.            Dim Mappings As New List(Of MappingInfo)
  408.  
  409.            ' Iterate the mappings.
  410.            For X As Integer = 0I To (Hosts.Count - 1I)
  411.  
  412.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  413.  
  414.                    ' Retrieve the mapping parts.
  415.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  416.  
  417.                    Dim MappingInfo As New MappingInfo
  418.                    With MappingInfo
  419.                        .HostName = Parts(1I)
  420.                        .IP = Parts(0I).Replace("#"c, String.Empty)
  421.                        .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  422.                        .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  423.                    End With ' MappingInfo
  424.  
  425.                    Mappings.Add(MappingInfo)
  426.  
  427.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  428.  
  429.            Next X
  430.  
  431.            Return Mappings
  432.  
  433.        End If
  434.  
  435.    End Function
  436.  
  437.    ''' <summary>
  438.    ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
  439.    ''' </summary>
  440.    ''' <param name="HostName">Indicates the Hostname.</param>
  441.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  442.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  443.    Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo
  444.  
  445.        If Not Me.FileExists() Then ' Hosts file does not exists.
  446.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  447.  
  448.        ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
  449.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))
  450.  
  451.        Else ' Get the mapping.
  452.  
  453.            ' Retrieve the HOSTS file content.
  454.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  455.            Dim MappingInfo As New MappingInfo
  456.  
  457.            ' Iterate the mappings.
  458.            For X As Integer = 0I To (Hosts.Count - 1I)
  459.  
  460.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  461.  
  462.                    ' Retrieve the mapping parts.
  463.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  464.  
  465.                    If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then
  466.  
  467.                        With MappingInfo
  468.                            .HostName = Parts(1I)
  469.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  470.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  471.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  472.                        End With ' MappingInfo
  473.  
  474.                        Exit For
  475.  
  476.                    End If ' Parts(1I).Equals(Hostname)...
  477.  
  478.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  479.  
  480.            Next X
  481.  
  482.            Return MappingInfo
  483.  
  484.        End If
  485.  
  486.    End Function
  487.  
  488.    ''' <summary>
  489.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
  490.    ''' matching the specified IP address.
  491.    ''' </summary>
  492.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  493.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  494.    Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)
  495.  
  496.        If Not Me.FileExists() Then ' Hosts file does not exists.
  497.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  498.  
  499.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  500.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  501.  
  502.        Else ' Get the mapping.
  503.  
  504.            ' Retrieve the HOSTS file content.
  505.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  506.            Dim Mappings As New List(Of MappingInfo)
  507.  
  508.            ' Iterate the mappings.
  509.            For X As Integer = 0I To (Hosts.Count - 1I)
  510.  
  511.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  512.  
  513.                    ' Retrieve the mapping parts.
  514.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  515.  
  516.                    If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then
  517.  
  518.                        Dim MappingInfo As New MappingInfo
  519.                        With MappingInfo
  520.                            .HostName = Parts(1I)
  521.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  522.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  523.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  524.                        End With ' MappingInfo
  525.  
  526.                        Mappings.Add(MappingInfo)
  527.  
  528.                    End If
  529.  
  530.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  531.  
  532.            Next X
  533.  
  534.            Return Mappings
  535.  
  536.        End If
  537.  
  538.    End Function
  539.  
  540.    ''' <summary>
  541.    ''' Checks whether a HostName is already mapped.
  542.    ''' </summary>
  543.    ''' <param name="HostName">Indicates the Hostname.</param>
  544.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  545.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  546.    Public Function IsMapped(ByVal HostName As String) As Boolean
  547.  
  548.        If Not Me.FileExists() Then ' Hosts file does not exists.
  549.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  550.  
  551.        Else
  552.            ' Retrieve the HOSTS file content.
  553.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  554.  
  555.            ' Iterate the mappings.
  556.            For X As Integer = 0I To (Hosts.Count - 1I)
  557.  
  558.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  559.  
  560.                    ' Retrieve the HostName of this mapping.
  561.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  562.  
  563.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  564.                        Return True
  565.                    End If ' Host.Equals(HostName)...
  566.  
  567.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  568.  
  569.            Next X
  570.  
  571.            Return False
  572.  
  573.        End If ' Not Me.Exists()...
  574.  
  575.    End Function
  576.  
  577.    ''' <summary>
  578.    ''' Checks whether a HostName is already mapped.
  579.    ''' </summary>
  580.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  581.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  582.    Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean
  583.  
  584.        Return Me.IsMapped(MappingInfo.HostName)
  585.  
  586.    End Function
  587.  
  588.    ''' <summary>
  589.    ''' Checks whether a HostName is already disabled.
  590.    ''' </summary>
  591.    ''' <param name="HostName">Indicates the Hostname.</param>
  592.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  593.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  594.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  595.    Public Function IsDisabled(ByVal HostName As String) As Boolean
  596.  
  597.        If Not Me.FileExists() Then ' Hosts file does not exists.
  598.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  599.  
  600.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  601.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  602.  
  603.        Else
  604.            ' Retrieve the HOSTS file content.
  605.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  606.            Dim Result As Boolean = False
  607.  
  608.            ' Iterate the mappings.
  609.            For X As Integer = 0I To (Hosts.Count - 1I)
  610.  
  611.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  612.  
  613.                    ' Retrieve the HostName of this mapping.
  614.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  615.  
  616.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  617.                        Result = Hosts(X).TrimStart.StartsWith("#"c)
  618.                        Exit For
  619.                    End If ' Host.Equals(HostName)...
  620.  
  621.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  622.  
  623.            Next X
  624.  
  625.            Return Result
  626.  
  627.        End If
  628.  
  629.    End Function
  630.  
  631.    ''' <summary>
  632.    ''' Checks whether a HostName is already disabled.
  633.    ''' </summary>
  634.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  635.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  636.    Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean
  637.  
  638.        Return Me.IsDisabled(MappingInfo.HostName)
  639.  
  640.    End Function
  641.  
  642.    ''' <summary>
  643.    ''' Checks whether the Hosts file exists.
  644.    ''' </summary>
  645.    ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
  646.    Public Function FileExists() As Boolean
  647.  
  648.        Return File.Exists(Me._HOSTSLocation)
  649.  
  650.    End Function
  651.  
  652.    ''' <summary>
  653.    ''' Creates the Hosts file.
  654.    ''' </summary>
  655.    Public Sub FileCreate()
  656.  
  657.        If Me.FileExists() Then
  658.            File.Delete(Me._HOSTSLocation)
  659.        End If
  660.  
  661.        File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)
  662.  
  663.    End Sub
  664.  
  665.    ''' <summary>
  666.    ''' Deletes the Hosts file.
  667.    ''' </summary>
  668.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  669.    Public Sub FileDelete()
  670.  
  671.        If Not Me.FileExists() Then
  672.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  673.  
  674.        Else
  675.            File.Delete(Me._HOSTSLocation)
  676.  
  677.        End If
  678.  
  679.    End Sub
  680.  
  681.    ''' <summary>
  682.    ''' Cleans the Hosts file.
  683.    ''' This removes all the mappings and adds the default file header.
  684.    ''' </summary>
  685.    Public Sub FileClean()
  686.  
  687.        Me.FileCreate()
  688.  
  689.    End Sub
  690.  
  691.    ''' <summary>
  692.    ''' Opens the Hosts file with the specified process.
  693.    ''' </summary>
  694.    ''' <param name="Process">
  695.    ''' Indicates the process location.
  696.    ''' Default value is: "notepad.exe".
  697.    ''' </param>
  698.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  699.    ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
  700.    Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")
  701.  
  702.        If Not Me.FileExists Then
  703.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  704.  
  705.        ElseIf Not File.Exists(Process) Then
  706.            Throw New FileNotFoundException("Process not found.", Process)
  707.  
  708.        Else
  709.            Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)
  710.  
  711.        End If
  712.  
  713.    End Sub
  714.  
  715. #End Region
  716.  
  717. #Region " Private Methods "
  718.  
  719.    ''' <summary>
  720.    ''' Validates an IP address.
  721.    ''' </summary>
  722.    ''' <param name="Address">The IP address.</param>
  723.    ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
  724.    Private Function ValidateIP(ByVal Address As String) As Boolean
  725.  
  726.        Dim IP As IPAddress = Nothing
  727.        Return IPAddress.TryParse(Address, IP)
  728.  
  729.    End Function
  730.  
  731. #End Region
  732.  
  733. End Class
  734.  
  735. #End Region

Ejemplos de uso:

Código
  1. Public Class HostsFileTestClass
  2.  
  3.    Private Sub HostsFileTestHandler() Handles MyBase.Shown
  4.  
  5.        ' Instance the HostsFile Class.
  6.        Dim Hosts As New HostsFile()
  7.  
  8.        ' Set a new mapping.
  9.        Dim Mapping As New HostsFile.MappingInfo
  10.        With Mapping
  11.            .HostName = "cuantodanio.es"
  12.            .IP = Hosts.LOCALHOST ' "127.0.0.1"
  13.            .Comment = "Test mapping comment."
  14.        End With
  15.  
  16.        With Hosts
  17.  
  18.            ' Delete the Host file.
  19.            If .FileExists Then
  20.                .FileDelete()
  21.            End If
  22.  
  23.            ' Create a new one Hosts file.
  24.            .FileCreate()
  25.  
  26.            ' Add some new mappings.
  27.            .Add(Mapping)
  28.            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
  29.  
  30.            ' Check if a mapping exists.
  31.            If .IsMapped(Mapping) Then
  32.                ' Disable the mapping.
  33.                .Disable(Mapping)
  34.            End If
  35.  
  36.            ' Check if an existint mapping is disabled.
  37.            If .IsDisabled("www.youtube.com") Then
  38.                ' Remove the mapping.
  39.                .Remove("www.youtube.com")
  40.            End If
  41.  
  42.            ' Open the HOSTS file with the specified text-editor.
  43.            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
  44.  
  45.        End With
  46.  
  47.        ' Get the IP of a mapped Hostname.
  48.        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
  49.  
  50.        ' Get all the hostname mappings
  51.        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
  52.        For Each MappingInfo As HostsFile.MappingInfo In Mappings
  53.  
  54.            Dim sb As New System.Text.StringBuilder
  55.            With sb
  56.                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
  57.                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
  58.                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
  59.                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
  60.            End With
  61.  
  62.            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
  63.  
  64.        Next MappingInfo
  65.  
  66.        ' Get all the hostname mappings that matches an ip address
  67.        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
  68.  
  69.    End Sub
  70.  
  71. End Class
« Última modificación: 11 Agosto 2014, 19:36 pm por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
No puedo imprimir: Falta el Archivo print.htm (Modificar desde el bios)
Multimedia
joseliz 0 1,779 Último mensaje 13 Noviembre 2005, 03:29 am
por joseliz
Como modificar un archivo host
Dudas Generales
Senior++ 3 10,870 Último mensaje 29 Diciembre 2010, 22:38 pm
por -- KiLiaN --
¿es posible modificar el archivo host desde mi web?
Desarrollo Web
simaticox 2 3,876 Último mensaje 22 Junio 2011, 16:47 pm
por simaticox
como modificar un archivo php desde otro
PHP
General Dmitry Vergadoski 4 3,103 Último mensaje 9 Agosto 2014, 03:01 am
por MinusFour
Piden modificar archivo Host para instalar programa full
Seguridad
Antaf7 3 3,534 Último mensaje 27 Abril 2018, 10:23 am
por akantor
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines