|
5841
|
Programación / .NET (C#, VB.NET, ASP) / Re: Obtener IP de una URL mediante VB. Net 2010
|
en: 4 Febrero 2015, 22:11 pm
|
en teoria, el primer valor del array es la IP, asi que no hace falta hacer el bucle for. TextBox1.Text = ip(0).ToString
Hombre en teoría es la IP ya que es una lista de direcciones, el problema es que a veces el primer item de la colección suele ser una IPv6, a mi también me dió problemas en el pasado.
Bueno, he escrito un ejemplo para ayudarte a obtener las IPv4 asociadas con "X" página Modo de empleo: Dim IPv4List As New List(Of String)(HostNameToIP("foro.elhacker.net", Net.Sockets.AddressFamily.InterNetwork)) Dim IPv6List As New List(Of String)(HostNameToIP("LOCALHOST", Net.Sockets.AddressFamily.InterNetworkV6)) MessageBox.Show(IPv4List(0)) ' Result: 108.162.205.73 MessageBox.Show(IPv6List(0)) ' Result: ::1
Source: ' HostName To IP ' By Elektro ' ' Usage Examples : ' MessageBox.Show(HostNameToIP("foro.elhacker.net", Net.Sockets.AddressFamily.InterNetwork).First) ' ''' <summary> ''' Gets the specified addresses associated to a Host. ''' </summary> ''' <param name="hotsName">The Host name.</param> ''' <param name="addressFamily">The address family.</param> ''' <returns>The addresses.</returns> ''' <exception cref="System.NotImplementedException">Address filtering not implemented yet.</exception> Public Function HostNameToIP(ByVal hotsName As String, ByVal addressFamily As Net.Sockets.AddressFamily) As IEnumerable(Of String) Dim hostInfo As Net.IPHostEntry = Net.Dns.GetHostEntry(hotsName) Dim addressList As IEnumerable(Of String) Try hostInfo = Net.Dns.GetHostEntry(hotsName) Select Case addressFamily Case Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.AddressFamily.InterNetworkV6 ' IPv4, IPv6. addressList = From address As Net.IPAddress In hostInfo.AddressList Where address.AddressFamily = addressFamily Select (address.ToString) Case Else Throw New NotImplementedException("Address filtering not implemented yet.") End Select Catch ex As Net.Sockets.SocketException Throw Catch ex As ArgumentNullException Throw Catch ex As Exception Throw End Try Return addressList End Function
|
|
|
5842
|
Programación / .NET (C#, VB.NET, ASP) / Re: Variable de longitud fija
|
en: 4 Febrero 2015, 21:33 pm
|
Si lo que quieres es limitar la cantidad de caracteres de un String, puedes utilizar el buffer de un StringBuilder: Dim sb As New StringBuilder(1, 5) ' máximo 5 caracteres. sb.Append("123456") ' 6 caracteres, dará error por sobrepasar el límite.
Si lo que quieres es un String de longitud variable pero que en principio contenga un número específico de caracteres, puedes usar el constructor del datatype String: Dim str As New String(" "c, 10)
Si lo que quieres es crear un string de longitud fija, siempre puedes crear tu propia extensión de método, o type: Modo de empleo: Dim fixedStr As FixedLengthString fixedStr = New FixedLengthString("", 10) MessageBox.Show("""" & fixedStr.ValueFixed & """") ' Result: " " fixedStr.ValueUnfixed = "12345" MessageBox.Show("""" & fixedStr.ValueFixed & """") ' Result: "1245 " fixedStr.ValueUnfixed = "1234567890abc" MessageBox.Show("""" & fixedStr.ValueFixed & """") ' Result: "1234567890"
Source: ' *********************************************************************** ' Author : Elektro ' Modified : 04-February-2015 ' *********************************************************************** ' <copyright file="FixedLengthString.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** ''' <summary> ''' Defines a <see cref="String"/> with a fixed length. ''' </summary> Public NotInheritable Class FixedLengthString #Region " Properties " ''' <summary> ''' Gets or sets the fixed string length. ''' </summary> ''' <value>The fixed string length.</value> Public Property FixedLength As Integer Get Return Me.fixedLength1 End Get Set(ByVal value As Integer) Me.fixedLength1 = value End Set End Property ''' <summary> ''' The fixed string length. ''' </summary> Private fixedLength1 As Integer ''' <summary> ''' Gets or sets the padding character thath fills the string. ''' </summary> ''' <value>The padding character thath fills the string.</value> Public Property PaddingChar As Char Get Return Me.paddingChar1 End Get Set(ByVal value As Char) Me.paddingChar1 = value End Set End Property ''' <summary> ''' The padding character thath fills the string. ''' </summary> Private paddingChar1 As Char ''' <summary> ''' Gets or sets the unmodified string. ''' </summary> ''' <value>The unmodified string.</value> Public Property ValueUnfixed As String Get Return Me.valueUnfixed1 End Get Set(ByVal value As String) Me.valueUnfixed1 = value End Set End Property ''' <summary> ''' The unmodified string. ''' </summary> Private valueUnfixed1 As String ''' <summary> ''' Gets the fixed string. ''' </summary> ''' <value>The fixed string.</value> Public ReadOnly Property ValueFixed As String Get Return Me.FixLength(Me.valueUnfixed1, Me.fixedLength1, Me.paddingChar1) End Get End Property #End Region #Region " Constructors " ''' <summary> ''' Prevents a default instance of the <see cref="FixedLengthString" /> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Initializes a new instance of the <see cref="FixedLengthString" /> class. ''' </summary> ''' <param name="value">The string value.</param> ''' <param name="fixedLength">The fixed string length.</param> ''' <param name="paddingChar">The padding character thath fills the string.</param> Public Sub New(ByVal value As String, ByVal fixedLength As Integer, Optional ByVal paddingChar As Char = " "c) Me.valueUnfixed1 = value Me.fixedLength1 = fixedLength Me.paddingChar1 = paddingChar End Sub #End Region #Region " Public Methods " ''' <summary> ''' Returns a <see cref="System.String" /> that represents this instance. ''' </summary> ''' <returns>A <see cref="System.String" /> that represents this instance.</returns> Public Overrides Function ToString() As String Return Me.ValueFixed End Function #End Region #Region " Private Methods " ''' <summary> ''' Fixes the length of the specified string. ''' </summary> ''' <param name="value">The string value.</param> ''' <param name="fixedLength">The fixed string length.</param> ''' <param name="paddingChar">The padding character thath fills the string.</param> ''' <returns>System.String.</returns> Private Function FixLength(ByVal value As String, ByVal fixedLength As Integer, ByVal paddingChar As Char) As String If (value.Length > fixedLength) Then Return value.Substring(0, fixedLength) Else Return value.PadRight(fixedLength, paddingChar) End If End Function #End Region End Class
|
|
|
5843
|
Programación / .NET (C#, VB.NET, ASP) / Re: Puedo grabar en un txt varios listbox ?
|
en: 4 Febrero 2015, 18:42 pm
|
Hola Luis Simplemente podrías serializar los datos en un archivo binario si tu intención es cargarlo de nuevo al programa, es algo muy facil, pero creo que no es el caso lo que quieres hacer, así que esto requiere mucha más escritura. He escrito este código hardcodeado, optimizado para un conjunto de listas con cantidad de items indefinida en cada lista, y con longitud de item indefinida. Nota: No lo he testeado mucho, quizás pueda haber agún error en ciertas circunstancias. Output: ListBox1 ListBox2 ListBox3 ListBox4 ******** ******** ******** ******** a1qwerty a2 a3 a4 qwertyqw erty -------- -------- -------- -------- b1 b2 b3 b4 -------- -------- -------- -------- c1 c3 -------- -------- -------- -------- d3 -------- -------- -------- --------
Source: Imports System.IO Imports System.Text Public Class TestForm Private Sub Test() Handles Button1.Click Dim lbs As ListBox() = {ListBox1, ListBox2, ListBox3, ListBox4} Dim spacing As Integer = 6 ' The horizontal spacing between columns. Dim filaPath As String = Path.Combine(Application.StartupPath, "Test.txt") Dim item1Parts As IEnumerable(Of String) = {} Dim item2Parts As IEnumerable(Of String) = {} Dim item3Parts As IEnumerable(Of String) = {} Dim item4Parts As IEnumerable(Of String) = {} Dim maxItemCount As Integer Dim maxItemPartCount As Integer Dim sb As New StringBuilder ' Get the max item count in listboxes. maxItemCount = (From lb As ListBox In lbs Order By lb.Items.Count Descending Select lb.Items.Count).First ' Write column names. sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}", New String(" "c, spacing), lbs(0).Name, lbs(1).Name, lbs(2).Name, lbs(3).Name)) ' Write column separator. sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}", New String(" "c, spacing), New String("*"c, lbs(0).Name.Length), New String("*"c, lbs(1).Name.Length), New String("*"c, lbs(2).Name.Length), New String("*"c, lbs(3).Name.Length))) ' Iterate listbox items. For index As Integer = 0 To (maxItemCount - 1) ' If item at index exist... If lbs(0).Items.Count > index Then item1Parts = SplitByLength(lbs(0).Items(index).ToString, lbs(0).Name.Length) End If If lbs(1).Items.Count > index Then item2Parts = SplitByLength(lbs(1).Items(index).ToString, lbs(1).Name.Length) End If If lbs(2).Items.Count > index Then item3Parts = SplitByLength(lbs(2).Items(index).ToString, lbs(2).Name.Length) End If If lbs(3).Items.Count > index Then item4Parts = SplitByLength(lbs(3).Items(index).ToString, lbs(3).Name.Length) End If If (item1Parts.Count > 1) OrElse (item2Parts.Count > 1) OrElse (item3Parts.Count > 1) OrElse (item4Parts.Count > 1) Then ' Get the max item count in itemParts. maxItemPartCount = (From col As IEnumerable(Of String) In {item1Parts, item2Parts, item3Parts, item4Parts} Order By col.Count Descending Select col.Count).First For x As Integer = 0 To (maxItemPartCount - 1) ' Write multiple items rows. sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}", New String(" "c, spacing), If(item1Parts.Count <= x, String.Empty, item1Parts(x) & New String(" "c, lbs(0).Name.Length - item1Parts(x).Length)), If(item2Parts.Count <= x, String.Empty, item2Parts(x) & New String(" "c, lbs(1).Name.Length - item2Parts(x).Length)), If(item3Parts.Count <= x, String.Empty, item3Parts(x) & New String(" "c, lbs(2).Name.Length - item3Parts(x).Length)), If(item4Parts.Count <= x, String.Empty, item4Parts(x) & New String(" "c, lbs(3).Name.Length - item4Parts(x).Length)))) Next Else ' Write simgle items row. sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}", New String(" "c, spacing), If(lbs(0).Items.Count <= index, String.Empty & New String(" "c, lbs(0).Name.Length), item1Parts.First & New String(" "c, lbs(0).Name.Length - item1Parts.First.Length)), If(lbs(1).Items.Count <= index, String.Empty & New String(" "c, lbs(1).Name.Length), item2Parts.First & New String(" "c, lbs(1).Name.Length - item2Parts.First.Length)), If(lbs(2).Items.Count <= index, String.Empty & New String(" "c, lbs(2).Name.Length), item3Parts.First & New String(" "c, lbs(2).Name.Length - item3Parts.First.Length)), If(lbs(3).Items.Count <= index, String.Empty & New String(" "c, lbs(3).Name.Length), item4Parts.First & New String(" "c, lbs(3).Name.Length - item4Parts.First.Length)))) End If ' Write horizontal grid. sb.AppendLine(String.Format("{1}{0}{2}{0}{3}{0}{4}", New String(" "c, spacing), New String("-"c, lbs(0).Name.Length), New String("-"c, lbs(1).Name.Length), New String("-"c, lbs(2).Name.Length), New String("-"c, lbs(3).Name.Length))) Next index File. WriteAllText(filaPath, sb. ToString, Encoding. Default) sb.Clear() Process.Start(filaPath) End Sub ' Split By Length ' By Elektro ' ''' <summary> ''' Splits a string by the specified character length. ''' </summary> ''' <param name="str">The string to split.</param> ''' <param name="length">The character length.</param> ''' <returns>IEnumerable(Of System.String).</returns> Private Function SplitByLength(ByVal str As String, ByVal length As Integer) As IEnumerable(Of String) Dim stringParts As New List(Of String) If str.Length > length Then Do Until str.Length <= length stringParts.Add(str.Substring(0, length)) str = str.Remove(0, length) Loop ' Add the last missing part (if any). If Not String.IsNullOrEmpty(str) Then stringParts.Add(str) End If Else stringParts.Add(str) End If Return stringParts End Function End Class
|
|
|
5845
|
Programación / Scripting / Re: Eliminar lineas que no cumplan cierta condición
|
en: 4 Febrero 2015, 15:53 pm
|
Si.. por ese lado lo estaba buscando.. pero la flag /V realiza la tarea inversa a lo que necesito.. Perdón, lo entendí al revés. Simplemente no escribas el parámetro /V y así obtendrás el resultado contrario. lote ctdo | 11/11/14 | 16 Cupones | 6.304,95 | 94,57 | lote ctdo | 12/11/14 | 11 Cupones | 3.029,72 | 45,44 | lote ctdo | 13/11/14 | 13 Cupones | 1.832,47 | 27,50 |
(Type "file.txt" | Findstr /V "^*")>"outputFile.txt" El comando FindStr utiliza patrones de expresiones regulares, en todo caso sería "^.*", pero la expresión que debes utilizar te la indiqué en el otro comentario. Lee sobre el uso de expresiones regulares (RegEx): http://en.wikipedia.org/wiki/Regular_expressionSaludos
|
|
|
5847
|
Programación / .NET (C#, VB.NET, ASP) / Re: Problemas a listar Archivos
|
en: 4 Febrero 2015, 15:24 pm
|
No crea el directorio con ese caracter y tambien lo de si existe esa ruta tampoco funciona(supongo que debe ser por ese caracter). En mi caso si que me crea correctamente la carpeta con dicho caracter, no se me ocurre porque motivo a ti no funciona. ¿la instrucción no lanza ninguna excepción?, en caso afirmativo, ¿cual es el mensaje de error y el stack trace?.
Asi me funciona, si sigo estoy equivocado corrigeme Hombre, un bloque try/catch anidado dentro de un bloque finally no es muy buena idea, el bloque finally contiene el código que será evaluado en todas las condiciones ocurra o no ocurra una excepción, puedes utilizarlo como un "On Error Resume Next", pero el bloque finally no se suele usar con la finalidad que le estás dando, sino más bien para hacer una limpieza, un cleanup, por ejemplo para asegurarse de liberar los recursos usados por objetos disposables: ' Un objeto disposable cualquiera. Dim obj As MemoryStream Try ' Instancio la class disposable. obj = New MemoryStream ' Intento leer un bloque de bytes en un buffer vacío, dará error. obj.Read(New Byte() {}, 0, 1) ' Las instrucciones de abajo no se procesarán ya que terminó la ejecución de este bloque debido al error. obj.Flush() obj.Close() Catch ex As Exception ' Controlar la excepción. MsgBox(ex.Message) Finally ' Asegurarse de liberar los recursos del objeto, se haya controlado o no la excepción. If obj IsNot Nothing Then obj.Flush() obj.Close() End If End Try
El código que has mostrado, yo lo dejaría así: EDITO: Bueno, también debo decir que la función GetFiles como ves devuelve una colección de objetos FileInfo, si no necesitas ningún dato más que la ruta del archivo entonces se puede simplificar bastante más para evitar algunas sentencias de LINQ innecesarias. Dim folderPath As String = "G:\" Dim sourceFolder As String = Path.Combine(folderPath, Convert.ToChar(160)) Dim destinyFolder As String = Path.Combine(folderPath, "Recuperado") Dim fileExts As IEnumerable(Of String) = {"docx", "pptx"} Dim fInfoCol As IEnumerable(Of FileInfo) Dim lvItems As ListViewItem() Try Directory.Move(sourceFolder, destinyFolder) Catch ' Omito cualquier excepción. End Try Try fInfoCol = GetFiles(folderPath, fileExts, SearchOption.AllDirectories) Catch ' Omito cualquier excepción. End Try lvItems = (From fInfo As FileInfo In fInfoCol Select New ListViewItem(fInfo.FullName)).ToArray With Me.ListView1 .BeginUpdate() .Items.AddRange(lvItems) .EndUpdate() End With ''' <summary> ''' Retrieves the files inside a directory, ''' containing the specified file extensions. ''' </summary> ''' <param name="folderPath">The directory path where to search files.</param> ''' <param name="fileExts">The file extensions to match.</param> ''' <param name="searchOption">The searching mode.</param> ''' <returns>IEnumerable(Of FileInfo).</returns> Public Shared Function GetFiles(ByVal folderPath As String, ByVal fileExts As IEnumerable(Of String), ByVal searchOption As SearchOption) As IEnumerable(Of FileInfo) ' Set all the file extensions to lower-case and ' Remove empty file extensions and ' Remove "*" and "." chars from beginning of the file extension. fileExts = From fileExt As String In fileExts Where Not String.IsNullOrEmpty(fileExt) Select fileExt.TrimStart({"*"c, "."c, " "c}).TrimEnd.ToLower Return From filePath As String In Directory.GetFiles(folderPath, "*", searchOption) Where If(Not String.IsNullOrEmpty(Path.GetExtension(filePath)), fileExts.Contains(Path.GetExtension(filePath).TrimStart("."c).ToLower), Nothing) Select New FileInfo(filePath) End Function
saludos
|
|
|
5850
|
Programación / .NET (C#, VB.NET, ASP) / Re: Problemas a listar Archivos
|
en: 4 Febrero 2015, 02:44 am
|
Shell("cmd.exe /c move /-y " & """" & "G:\" & ChrW(&HA0) & """" & " G:\Recuperado")
Buf...! Queda totalmente prohibido a partir de hoy utilizar Batch bajo .Net en este foro. No, en serio, no utilices herramientas primitivas como la consola de Windows + comandos de Batch, es innecesario y no te aporta ningún control sobre dicha acción, prueba así: Imports System.IO
Dim sourceFolder As String = Path.Combine("C:\", Convert.ToChar(160)) Dim destinyFolder As String = Path.Combine("C:\", "Recuperado") Try Directory.CreateDirectory(sourceFolder) ' Creo la carpeta para reproducir el problema que has descrito. If Directory.Exists(sourceFolder) Then ' Si el directorio existe... ' Lo muevo. Directory.Move(sourceFolder, destinyFolder) End If Catch ex As Exception Throw End Try
saludos
|
|
|
|
|
|
|