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

 

 


Tema destacado: Curso de javascript por TickTack


  Mostrar Temas
Páginas: [1]
1  Programación / .NET (C#, VB.NET, ASP) / Leer archivo txt y validar estructura en: 24 Febrero 2016, 22:46 pm
Saludos amigos,

Tiempo sin andar por acá.

En esta oportunidad vengo a hacerles una consulta; necesito hacer tres cosas:
1.- Leer la estructura de un archivo txt cuyos campos están separados por punto y coma.
2.- Leer cada campo del registro y validar si el campo tiene datos o está vacio, si tiene valores numericos cuando debe ser alfanumericos.
3.- Si encuentra errores en los registros ir guardandolos en otro txt y al fina dar un resumen, es decir, se procesaron X registros los cuales Y tienen errores e indicar cada registro con su error al lado

Alguien podría darme una mano con esto?

Gracias mil desde ya.

2  Programación / .NET (C#, VB.NET, ASP) / Leer nombre de carpetas en: 9 Noviembre 2015, 14:50 pm
Saludos amigos,

Tengo una función que lee el nombre de carpetas tomando en cuenta la selección de un mes, y las mueve a una carpeta principal.

Esta función fue desarrollada por Elektro y aquí se las comparto.

Código
  1.        Public Sub MoveDateDirectories(ByVal year As Integer,
  2.                                       ByVal month As Integer,
  3.                                       ByVal dateFormat As String,
  4.                                       ByVal sourceDir As String,
  5.                                       ByVal targetDir As String)
  6.            If (CStr(year).Length <> 4I) Then
  7.                Throw New ArgumentOutOfRangeException(paramName:="year", message:="A value of 4 digits' is required.")
  8.                'ElseIf (month < 1I) OrElse (month > 12I) Then
  9.                '    Throw New ArgumentOutOfRangeException(paramName:="month", message:="A value from range '1' to '12' is required.")
  10.                'ElseIf (dateFormat.Replace("y", "").Replace("M", "").Replace("d", "").Length <> 0) Then
  11.                '    Throw New NotImplementedException(message:="Specified date format is not implemented, only 'yyyy', 'MM' and 'dd' are interchangeable.")
  12.                'ElseIf Not Directory.Exists(sourceDir) Then
  13.                '    Throw New DirectoryNotFoundException(message:=String.Format("Source directory not found: '{0}'", targetDir))
  14.                'ElseIf Not Directory.Exists(targetDir) Then
  15.                '    Throw New DirectoryNotFoundException(message:=String.Format("Target directory not found: '{0}'", targetDir))
  16.            Else
  17.                Dim sourceDirInfo As New DirectoryInfo(sourceDir)
  18.                Dim targetDirInfo As New DirectoryInfo(targetDir)
  19.                ' Obtengo una colección con los nombres de directorio con el formato de fecha especificado. (ej. de Octubre 2015:  20151001 ... 20151031)
  20.                Dim dateDirNames As IEnumerable(Of String) =
  21.                    From day As Integer In Enumerable.Range(1, DateTime.DaysInMonth(year, month))
  22.                    Select dateFormat.Replace("yyyy", CStr(year)).
  23.                                                  Replace("MM", CStr(month).PadLeft(2, "0"c)).
  24.                                                  Replace("dd", CStr(day).PadLeft(2, "0"c))
  25.                ' Obtengo una colección con las rutas absolutas de los directorios que cumplen los requisitos.
  26.                Dim directories As IEnumerable(Of DirectoryInfo) =
  27.                    From dirInfo As DirectoryInfo In sourceDirInfo.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)
  28.                    Where dateDirNames.Contains(dirInfo.Name)
  29.                ' Un simple mensaje de información o aviso cuando no se encuentra ningún directorio el cual mover.
  30.                If (Not directories.Any) Then
  31.                    Dim msg As String = String.Format("No ha sido encontrado ningún directorio en '{0}' que cumpla las condiciones de formato de fecha.", sourceDirInfo.FullName)
  32.                    MessageBox.Show(msg, " ", MessageBoxButtons.OK, MessageBoxIcon.Information)
  33.                Else
  34.                    ' Por último, muevo los directorios que cumplieron las condiciones de formato de fecha.
  35.                    For Each dirInfo As DirectoryInfo In directories
  36.                        Debug.WriteLine(String.Format("Moviendo: {0}", dirInfo.FullName))
  37.                        Try
  38.                            dirInfo.MoveTo(Path.Combine(targetDirInfo.FullName, dirInfo.Name))
  39.                        Catch ex As Exception
  40. #If DEBUG Then
  41.                            Throw
  42. #Else
  43.                        MessageBox.Show(ex.Message & Environment.NewLine & ex.StackTrace, "By Elektro", MessageBoxButtons.OK, MessageBoxIcon.Error)
  44. #End If
  45.                        End Try
  46.                    Next dirInfo
  47.                    '                MessageBox.Show("Operación finalizada.", "By Elektro", MessageBoxButtons.OK, MessageBoxIcon.Information)
  48.                End If ' Not directories.Any
  49.            End If ' dateFormat...
  50.        End Sub
  51.  


Esta trabaja perfecto sin problemas; salvo que ahora necesito adecuarla de manera que sea posible mover días, es decir, si el usuario selecciona desde el 01-12-2015 hasta el 15-12-2015 (ambos inclusive); el proceso solo mueva esos días.

Alguien podría orientarme de como adecuar esta función para que haga lo que necesito?

Desde ya mil gracias...
3  Programación / .NET (C#, VB.NET, ASP) / Cambiar palabras de un archivo TXT en: 23 Octubre 2015, 17:24 pm
Saludos a todos;

El siguiente script hace un merge de archivos TXT:
Código
  1.   Public Sub FindAndMergeFiles(ByVal sourceDir As String)
  2.        Dim fileNames As String() =
  3.        {
  4.            "CM.txt", "GL.txt",
  5.            "IMP6000.txt", "IMP6001.txt", "IMP6002.txt", "IMP6003.txt"
  6.        }
  7.        Dim curFilename As String = String.Empty
  8.        For Each topDir As DirectoryInfo In New DirectoryInfo(sourceDir).GetDirectories("*", SearchOption.TopDirectoryOnly)
  9.            ' Elimino los archivos principales ("...\topDir\CM.txt", "...\topDir\GL.txt", etc...) de sesiones anteriores.
  10.            For Each txtfile As FileInfo In topDir.GetFiles("*.txt", SearchOption.TopDirectoryOnly)
  11.                If fileNames.Contains(txtfile.Name, StringComparer.OrdinalIgnoreCase) Then
  12.                    txtfile.Delete()
  13.                End If
  14.            Next txtfile
  15.            For Each subDir As DirectoryInfo In topDir.GetDirectories("*", SearchOption.AllDirectories)
  16.                For Each txtfile As FileInfo In subDir.GetFiles("*.txt", SearchOption.AllDirectories)
  17.                    If fileNames.Contains(txtfile.Name, StringComparer.OrdinalIgnoreCase) Then
  18.                        curFilename = fileNames.First(Function(filename) filename.Equals(txtfile.Name, StringComparison.OrdinalIgnoreCase))
  19.                        Using sr As StreamReader = txtfile.OpenText
  20.                            Using sw As New StreamWriter(Path.Combine(topDir.FullName, curFilename), append:=True, encoding:=Encoding.Default, bufferSize:=128)
  21.                                sw.WriteLine(sr.ReadToEnd)
  22.                            End Using ' sw
  23.                        End Using ' sr
  24.                    End If
  25.                Next txtfile
  26.            Next subDir
  27.        Next topDir
  28.  

Ahora bien en el formulario que usa ese script hay un selector que indica dos opciones A y B; donde si la opción B es la que ha sido seleccionada es nesario buscar en dos archivos particulares una palabra y cambiarla por otra, entiendo que la funcion sería mas o menos así:

Código
  1. Private Sub ReemplazaTexto(ByVal Fichero As String, ByVal Texto_Busca As String, ByVal Texto_Reemplaza As String)
  2.    Dim Reader As New StreamReader(Fichero)
  3.    Dim Content As String = Reader.ReadToEnd()
  4.    Reader.Close()
  5.    Content = Regex.Replace(Content, Texto_Busca, Texto_Reemplaza)
  6.    Dim Writer As New StreamWriter(FicheroNuevo)
  7.    Writer.Write(Content)
  8.    writer.Close()
  9. End Sub
  10.  

Ahora lo que quedaría es que despues que ejecuto el merge es preguntar que opción del combobox está seleccionada, que sería así:
Código
  1. 'El usuario selecciono la opcion para cambiar texto
  2. If ComboBox1.SelectedIndex = 0 Then
  3.          reemplazatexto("AR.txt","TXTB1","TXTN")
  4.          reemplazatexto("AR.txt","TXTB2","TXTN")
  5.          reemplazatexto("BR.txt","TXTB1","TXTN")
  6.          reemplazatexto("BR.txt","TXTB2","TXTN")
  7. Else          
  8.         return
  9. End If
  10.  

Creo que así sería; pero si alguien tiene uuna mejor idea será bien recibida.

Desde ya mil gracias.
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines