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

 

 


Tema destacado: Tutorial básico de Quickjs


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [C#] Editar líneas de archivos de texto
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [C#] Editar líneas de archivos de texto  (Leído 4,733 veces)
DeMoNcRaZy


Desconectado Desconectado

Mensajes: 420


$~*|_


Ver Perfil
[C#] Editar líneas de archivos de texto
« en: 2 Septiembre 2015, 23:10 pm »

Buenas,

Tengo un problema a la hora de modificar las líneas (textos) que hay dentro de un archivo .txt

Código
  1. using (StreamWriter fileWrite = new StreamWriter(@"C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt"))
  2.                {
  3.                    using (StreamReader fileRead = new StreamReader(@"C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt"))
  4.                    {
  5.                        string line;
  6.                        string txtUsuario;
  7.  
  8.                        while ((line = fileRead.ReadLine()) != null)
  9.                        {
  10.                            string[] datos = line.Split(new char[] { ' ' });
  11.                            if (datos[0] != txtUsuario.Text)
  12.                            {
  13.                                fileWrite.WriteLine(line);
  14.                            }
  15.  
  16.                        }
  17.                    }
  18.                }
  19.  

Lo cual intento leer 2 líneas que tengo introducidas del archivo así:

Código:
Nombre: Bruce
Apellidos: Lee

Pero en txtUsuario.Txt me da el siguiente error:

Código:
Use of unassigned local variable "txtUsuario"

Por lo que no me deja editar los dos campos que tengo introducidos en el archivo.

Agradezco cualquier información adicional.
Me quedé un poco trabado en esta parte.

Gracias.

Saludos.


En línea

Esta página web no está disponible - Google Chrome
someRandomCode

Desconectado Desconectado

Mensajes: 250



Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #1 en: 2 Septiembre 2015, 23:16 pm »

Yuse lo que te dice es que estas usando la variable txtUsuario sin haberle asignado valor antes


En línea

DeMoNcRaZy


Desconectado Desconectado

Mensajes: 420


$~*|_


Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #2 en: 2 Septiembre 2015, 23:29 pm »

Si le asigno un valor no me muestra nada o me salta este error:



En esta línea:

Código
  1. using (StreamReader fileRead = new StreamReader(@"C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt"))

Que creo que puede ser por que estoy llamando dos veces al mismo proceso dentro del mismo.

Lo que quiero saber si esta es la manera correcta de editar dichas líneas dentro de un archivo de texto.

Saludos.
En línea

Esta página web no está disponible - Google Chrome
someRandomCode

Desconectado Desconectado

Mensajes: 250



Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #3 en: 2 Septiembre 2015, 23:39 pm »

Y si modificas el otro proceso para que lo abra en modo compartido?
https://msdn.microsoft.com/en-us/library/y973b725%28v=vs.110%29.aspx
Ponle de modo ReadWrite en comparticion solo por las dudas:
https://msdn.microsoft.com/en-us/library/system.io.fileshare%28v=vs.110%29.aspx
En línea

DeMoNcRaZy


Desconectado Desconectado

Mensajes: 420


$~*|_


Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #4 en: 3 Septiembre 2015, 00:37 am »

Gracias por las molestias/ayuda.

Al final he encontrado la manera de hacerlo de una manera más eficaz.

Código
  1. string path = @"C:\\Users\\Usuario\\Desktop\\Textos\\carpetaArchivos\\" + nombreArchivo + ".txt";
  2.  
  3.            string nombre = "Nombre: ";
  4.            string apellidos = "Apellidos: ";
  5.  
  6.            Console.WriteLine("Introduzca el nombre:");
  7.            string nuevoNombre = Console.ReadLine();
  8.            Console.WriteLine("Introduzca el/los apellidos:");
  9.            string nuevoApellido = Console.ReadLine();
  10.  
  11.            var lines = File.ReadAllLines(path);
  12.  
  13.            var replaced = lines.Select(x =>
  14.            {
  15.                if (x.StartsWith(nombre))
  16.                    return nombre + nuevoNombre;
  17.                if (x.StartsWith(apellidos))
  18.                    return apellidos + nuevoApellido;
  19.                return x;
  20.            });
  21.  
  22.            File.WriteAllLines(path, replaced);
  23.  
  24.            Console.WriteLine("El archivo se ha modificado correctamente.");
  25.  

Saludos.
En línea

Esta página web no está disponible - Google Chrome
DarK_FirefoX


Desconectado Desconectado

Mensajes: 1.263


Be the change you wanna see in te world


Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #5 en: 4 Septiembre 2015, 17:31 pm »

Yuse lo que te dice es que estas usando la variable txtUsuario sin haberle asignado valor antes

Exacto estás declarando la variable txtUsuario y no le estás asignando ningun valor y luego estas comparando esa variable con otra.

Pero no solo eso!

Código
  1. if (datos[0] != txtUsuario.Text)

la clase string no contiene ninguna definición de propiedad o método de extensión que sea Text, así que en principio esto te daría error de compilación (De hecho, el intelissense (si estás en VS) te lo debe mostrar como error)

Salu2s
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: [C#] Editar líneas de archivos de texto
« Respuesta #6 en: 5 Septiembre 2015, 15:54 pm »

El problema lo has solucionado de la manera más incorrecta, ya que no has aprendido a cómo solucionar los errores que tenías, simplemente has preferido optar por utilizar otra metodología distinta para evitar encontrarte con esos errores. ¿te compensa?, piensalo.

Lee el comentario de @Dark_Firefox y si no entiendes algo pregunta hasta que lo entiendas, por que de lo contrario el mismo conflicto te va a volver a suceder una y otra vez y no sabrás por qué, ya que un objeto sin inicializar (accidentálmente) es un despiste humano muy típico, y algo muy sencillo de comprender y solucionar.



me salta este error:



En esta línea:
Código
  1. using (StreamReader fileRead = new StreamReader(@"C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt"))

El mensaje de error se explica por si mismo, justo antes de esa instrucción ya tienes el archivo abierto con esto:
Citar
Código
  1. Using fileWrite As New StreamWriter("C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt")

Cuando "abres" un archivo se crea un handle especial en el sistema, el cual no puedes compartir con otro proceso (ni con tu propio proceso) a menos que así lo indiques, entonces no puedes esperar mantener abierto el archivo para su lectura mientras al mismo tiempo intentas abrirlo de nuevo para su escritura, sin embargo, si que puedes mantenerlo abierto con ambos permisos al mismo tiempo.

Lo que puedes hacer es utilizar el overload que toma cómo parámetro un stream, de la siguiente manera:

Código
  1. using (FileStream fs = File.Open("C:\\file.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
  2.  
  3. using (StreamReader sr = new StreamReader(stream: fs, encoding: Encoding.Default)) {
  4.  
  5. using (StreamWriter sw = new StreamWriter(stream: fs, encoding: Encoding.Default)) {
  6.  
  7. while (!(sr.EndOfStream)) {
  8.  
  9.                                string line = sr.ReadLine;
  10.                                // Leer o escribir en el stream...
  11.  
  12. }
  13.  
  14. } // sw
  15.  
  16. } // sr
  17.  
  18. } // fs

De todas formas yo optaría por evitar el uso de StreamReader, StreamWriter y demás, ya que tu intención no es mantener el archivo abierto mientras le haces cambios durante el tiempo de vida del proceso (ej. un sistema de logging), es un cambio pequeño y sencillo así que no requiere más que la solución que encontraste usando LINQ, aunque es imprecisa, pues yo, siguiendo la linea del último ejemplo, y siendo consciente de "donde está todo escrito" y cómo lo está, sin posibilidad a errores, lo haría más bien así:

Código
  1.    <Serializable>
  2.    Public NotInheritable Class Contact
  3.  
  4.        Public Property Name As String
  5.        Public Property Surname As String
  6.  
  7.    End Class
  8.  
  9.    Private Function GetContact(ByVal filePath As String) As Contact
  10.  
  11.        Const FieldName As String = "Nombre:"
  12.        Const FieldSurname As String = "Apellidos:"
  13.  
  14.        Dim lines As IEnumerable(Of String) = File.ReadAllLines(filePath, Encoding.Default)
  15.  
  16.        If (lines.Count <> 2) Then
  17.            Throw New Exception(message:="Número incorrecto de lineas.")
  18.        End If
  19.  
  20.        Dim currentName As String =
  21.            lines(0).Substring(lines(0).IndexOf(FieldName, StringComparison.OrdinalIgnoreCase) + FieldName.Length).
  22.                 Trim(" "c)
  23.  
  24.        Dim currentSurname As String =
  25.            lines(1).Substring(lines(1).IndexOf(FieldSurname, StringComparison.OrdinalIgnoreCase) + FieldSurname.Length).
  26.                 Trim(" "c)
  27.  
  28.        Return New Contact With
  29.               {
  30.                   .Name = currentName,
  31.                   .Surname = currentSurname
  32.               }
  33.  
  34.    End Function
  35.  
  36.    Private Sub SetContact(ByVal filepath As String, ByVal contact As Contact)
  37.  
  38.        Const FieldName As String = "Nombre"
  39.        Const FieldSurname As String = "Apellidos"
  40.  
  41.        Dim sb As New StringBuilder
  42.        sb.AppendLine(String.Format("{0}: {1}", FieldName, contact.Name))
  43.        sb.AppendLine(String.Format("{0}: {1}", FieldSurname, contact.Surname))
  44.  
  45.        File.WriteAllText(filepath, sb.ToString, Encoding.Default)
  46.  
  47.    End Sub

Para darle el siguiente uso:

Código
  1. Dim filePath As String = "C:\file.txt"
  2.  
  3. Dim currentContact As Contact = GetContact(filePath)
  4.  
  5. Console.WriteLine(String.Format("Name...: {0}", currentcontact.Name))
  6. Console.WriteLine(String.Format("Surname: {0}", currentcontact.Surname))
  7.  
  8. currentContact.Name = "Pepito"
  9. currentContact.Surname = "Palotes"
  10.  
  11. Me.SetContact("C:\file.txt", currentContact)

Código traducido a C#:

Código
  1. [Serializable()]
  2. public sealed class Contact
  3. {
  4.  
  5. public string Name { get; set; }
  6. public string Surname { get; set; }
  7.  
  8. }

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Text;
  9.  
  10. public sealed class Form1 : Form
  11. {
  12.  
  13. private void Test()
  14. {
  15. string filePath = "C:\\file.txt";
  16.  
  17. Contact currentContact = GetContact(filePath);
  18.  
  19. Console.WriteLine(string.Format("Name...: {0}", currentContact.Name));
  20. Console.WriteLine(string.Format("Surname: {0}", currentContact.Surname));
  21.  
  22. currentContact.Name = "Pepito";
  23. currentContact.Surname = "Palotes";
  24.  
  25. this.SetContact("C:\\file.txt", currentContact);
  26.  
  27. }
  28.  
  29. private Contact GetContact(string filePath)
  30. {
  31.  
  32. const string FieldName = "Nombre:";
  33. const string FieldSurname = "Apellidos:";
  34.  
  35. IEnumerable<string> lines = File.ReadAllLines(filePath, Encoding.Default);
  36.  
  37. if ((lines.Count != 2)) {
  38. throw new Exception(message: "Número incorrecto de lineas.");
  39. }
  40.  
  41. string currentName = lines(0).Substring(lines(0).IndexOf(FieldName, StringComparison.OrdinalIgnoreCase) + FieldName.Length).Trim(' ');
  42.  
  43. string currentSurname = lines(1).Substring(lines(1).IndexOf(FieldSurname, StringComparison.OrdinalIgnoreCase) + FieldSurname.Length).Trim(' ');
  44.  
  45. return new Contact {
  46. Name = currentName,
  47. Surname = currentSurname
  48. };
  49.  
  50. }
  51.  
  52.  
  53. private void SetContact(string filepath, Contact contact)
  54. {
  55. const string FieldName = "Nombre";
  56. const string FieldSurname = "Apellidos";
  57.  
  58. StringBuilder sb = new StringBuilder();
  59. sb.AppendLine(string.Format("{0}: {1}", FieldName, contact.Name));
  60. sb.AppendLine(string.Format("{0}: {1}", FieldSurname, contact.Surname));
  61.  
  62. File.WriteAllText(filepath, sb.ToString, Encoding.Default);
  63.  
  64. }
  65.  
  66. }
  67.  
  68. //=======================================================
  69. //Service provided by Telerik (www.telerik.com)
  70. //=======================================================



PEEEEEEEEERO... en mi humilde opinión debo mencionar que la metodología que empleas en el primer y el segundo ejemplo que has mostrado (y también la que yo he empleado en el último ejemplo de arriba) en realidad es bastante primitiva, ya que aprendiendo a cómo manipular un archivo de texto tipo "contacto" de esa manera en realidad no aprendes nada útil. Si fuese para otra cosa, tal vez, pero para contactos lo que deberías usar, repito, en mi opinión, sería la serialización de datos, no por la ofuscación de datos, sino simplemente por que aporta mucho más control y seguridad sobre las acciones que haces en el archivo, en lugar de tener que estar "partiendo" y evaluando string a string ya que hay muchos posibles fallos que necesitarían ser controlados manualmente. Al menos deberías probar la serialización de datos para familiarizarte con esto.

Un ejemplo:

(si quieres que los datos sean legibles, puedes utilizar la serialización XML)

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 05-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="SerializationUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10.  
  11.  
  12. ' ESTA CLASE ESTÁ PARCIALMENTE DEFINIDA (O PARCIALMENTE CAPADA) SOLO PARA SATISFACER LAS NECESIDADES DE ESTA PREGUNTA.
  13.  
  14.  
  15.  
  16. #Region " Imports "
  17.  
  18. Imports System
  19. Imports System.Data
  20. Imports System.IO
  21. Imports System.Linq
  22. Imports System.Runtime.Serialization.Formatters.Binary
  23. Imports System.Xml.Serialization
  24.  
  25. #End Region
  26.  
  27. ''' <summary>
  28. ''' Contains related serialization utilities.
  29. ''' </summary>
  30. Public NotInheritable Class SerializationUtil
  31.  
  32. #Region " Constructors "
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    Private Sub New()
  40.    End Sub
  41.  
  42. #End Region
  43.  
  44. #Region " Private Methods "
  45.  
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    ''' <exception cref="System.ArgumentException">
  48.    ''' Wrong Serialization Format.
  49.    ''' </exception>
  50.    ''' ----------------------------------------------------------------------------------------------------
  51.    <DebuggerStepThrough>
  52.    <DebuggerHidden>
  53.    Private Shared Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object
  54.  
  55.        Select Case format
  56.  
  57.            Case SerializationFormat.Binary
  58.                Return New BinaryFormatter
  59.  
  60.            Case SerializationFormat.Xml
  61.                Return New XmlSerializer(type:=GetType(T))
  62.  
  63.            Case Else
  64.                Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")
  65.  
  66.        End Select
  67.  
  68.    End Function
  69.  
  70. #End Region
  71.  
  72. #Region " Public Methods "
  73.  
  74.    ''' ----------------------------------------------------------------------------------------------------
  75.    ''' <summary>
  76.    ''' Serializes the data of an Object to the specified file, using the specified serialization format.
  77.    ''' </summary>
  78.    ''' ----------------------------------------------------------------------------------------------------
  79.    ''' <typeparam name="T">
  80.    ''' </typeparam>
  81.    '''
  82.    ''' <param name="obj">
  83.    ''' The object to be serialized.
  84.    ''' </param>
  85.    '''
  86.    ''' <param name="filepath">
  87.    ''' The filepath where to save the serialized data.
  88.    ''' </param>
  89.    '''
  90.    ''' <param name="format">
  91.    ''' The serialization format.
  92.    ''' </param>
  93.    ''' ----------------------------------------------------------------------------------------------------
  94.    <DebuggerStepThrough>
  95.    <DebuggerHidden>
  96.    Public Shared Sub Serialize(Of T)(ByVal obj As T,
  97.                                      ByVal filepath As String,
  98.                                      ByVal format As SerializationFormat)
  99.  
  100.        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)
  101.  
  102.        Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)
  103.  
  104.            Select Case serializer.GetType
  105.  
  106.                Case GetType(BinaryFormatter)
  107.                    DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)
  108.  
  109.                Case GetType(XmlSerializer)
  110.                    DirectCast(serializer, XmlSerializer).Serialize(fs, obj)
  111.  
  112.            End Select
  113.  
  114.        End Using
  115.  
  116.    End Sub
  117.  
  118.    ''' ----------------------------------------------------------------------------------------------------
  119.    ''' <summary>
  120.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  121.    ''' </summary>
  122.    ''' ----------------------------------------------------------------------------------------------------
  123.    ''' <typeparam name="T">
  124.    ''' </typeparam>
  125.    '''
  126.    ''' <param name="filepath">
  127.    ''' The filepath where from deserialize the serialized data.
  128.    ''' </param>
  129.    '''
  130.    ''' <param name="format">
  131.    ''' The serialization format.
  132.    ''' </param>
  133.    ''' ----------------------------------------------------------------------------------------------------
  134.    <DebuggerStepThrough>
  135.    <DebuggerHidden>
  136.    Public Shared Function Deserialize(Of T)(ByVal filepath As String,
  137.                                             ByVal format As SerializationFormat) As T
  138.  
  139.        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)
  140.  
  141.        Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
  142.  
  143.            Select Case serializer.GetType
  144.  
  145.                Case GetType(BinaryFormatter)
  146.                    Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T)
  147.  
  148.                Case GetType(XmlSerializer)
  149.                    Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T)
  150.  
  151.            End Select
  152.  
  153.        End Using
  154.  
  155.    End Function
  156.  
  157.    ''' ----------------------------------------------------------------------------------------------------
  158.    ''' <summary>
  159.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  160.    ''' </summary>
  161.    ''' ----------------------------------------------------------------------------------------------------
  162.    ''' <typeparam name="T">
  163.    ''' </typeparam>
  164.    '''
  165.    ''' <param name="filepath">
  166.    ''' The filepath where from deserialize the serialized data.
  167.    ''' </param>
  168.    '''
  169.    ''' <param name="format">
  170.    ''' The serialization format.
  171.    ''' </param>
  172.    ''' ----------------------------------------------------------------------------------------------------
  173.    <DebuggerStepThrough>
  174.    <DebuggerHidden>
  175.    Public Shared Sub Deserialize(Of T)(ByRef refObj As T,
  176.                                        ByVal filepath As String,
  177.                                        ByVal format As SerializationFormat)
  178.  
  179.        refObj = SerializationUtil.Deserialize(Of T)(filepath, format)
  180.  
  181.    End Sub
  182.  
  183. #End Region
  184.  
  185. End Class

Modo de empleo:

Código
  1. <Serializable>
  2. Public NotInheritable Class Contact
  3.  
  4.    Public Property Name As String
  5.    Public Property Surname As String
  6.  
  7. End Class

Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    Private Sub Form1_Load() Handles MyBase.Shown
  4.        Test()
  5.    End Sub
  6.  
  7.    Private Sub Test()
  8.  
  9.        Dim filePath As String = "C:\file.dat"
  10.  
  11.        Dim currentContact As Contact = GetContact(filePath)
  12.  
  13.        Console.WriteLine(String.Format("Name...: {0}", currentContact.Name))
  14.        Console.WriteLine(String.Format("Surname: {0}", currentContact.Surname))
  15.  
  16.        currentContact.Name = "Pepito"
  17.        currentContact.Surname = "Palotes"
  18.  
  19.        Me.SetContact("C:\file.dat", currentContact)
  20.  
  21.    End Sub
  22.  
  23.    Private Function GetContact(ByVal filePath As String) As Contact
  24.  
  25.        Return SerializationUtil.Deserialize(Of Contact)(filePath, SerializationFormat.Binary)
  26.  
  27.    End Function
  28.  
  29.    Private Sub SetContact(ByVal filepath As String, ByVal contact As Contact)
  30.  
  31.        SerializationUtil.Serialize(contact, filepath, SerializationFormat.Binary)
  32.  
  33.    End Sub
  34.  
  35. End Class

Todo traducido a C#:
Código
  1. // ***********************************************************************
  2. // Author   : Elektro
  3. // Modified : 05-September-2015
  4. // ***********************************************************************
  5. // <copyright file="SerializationUtil.vb" company="Elektro Studios">
  6. //     Copyright (c) Elektro Studios. All rights reserved.
  7. // </copyright>
  8. // ***********************************************************************
  9.  
  10.  
  11.  
  12. // ESTA CLASE ESTÁ PARCIALMENTE DEFINIDA (O PARCIALMENTE CAPADA) SOLO PARA SATISFACER LAS NECESIDADES DE ESTA PREGUNTA.
  13.  
  14.  
  15.  
  16. #region " Usings "
  17.  
  18. using Microsoft.VisualBasic;
  19. using System;
  20. using System.Collections;
  21. using System.Collections.Generic;
  22. using System.Data;
  23. using System.Diagnostics;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Runtime.Serialization.Formatters.Binary;
  27. using System.Xml.Serialization;
  28.  
  29. #endregion
  30.  
  31. /// <summary>
  32. /// Contains related serialization utilities.
  33. /// </summary>
  34. public sealed class SerializationUtil
  35. {
  36.  
  37. #region " Constructors "
  38.  
  39. /// ----------------------------------------------------------------------------------------------------
  40. /// <summary>
  41. /// Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
  42. /// </summary>
  43. /// ----------------------------------------------------------------------------------------------------
  44. private SerializationUtil()
  45. {
  46. }
  47.  
  48. #endregion
  49.  
  50. #region " Private Methods "
  51.  
  52. /// ----------------------------------------------------------------------------------------------------
  53. /// <exception cref="System.ArgumentException">
  54. /// Wrong Serialization Format.
  55. /// </exception>
  56. /// ----------------------------------------------------------------------------------------------------
  57. [DebuggerStepThrough()]
  58. [DebuggerHidden()]
  59. private static object GetSerializer<T>(SerializationFormat format)
  60. {
  61.  
  62. switch (format) {
  63.  
  64. case SerializationFormat.Binary:
  65.  
  66. return new BinaryFormatter();
  67. case SerializationFormat.Xml:
  68.  
  69. return new XmlSerializer(type: typeof(T));
  70. default:
  71.  
  72. throw new ArgumentException(message: "Wrong Serialization Format.", paramName: "serializationFormat");
  73. }
  74.  
  75. }
  76.  
  77. #endregion
  78.  
  79. #region " Public Methods "
  80.  
  81. /// ----------------------------------------------------------------------------------------------------
  82. /// <summary>
  83. /// Serializes the data of an Object to the specified file, using the specified serialization format.
  84. /// </summary>
  85. /// ----------------------------------------------------------------------------------------------------
  86. /// <typeparam name="T">
  87. /// </typeparam>
  88. ///
  89. /// <param name="obj">
  90. /// The object to be serialized.
  91. /// </param>
  92. ///
  93. /// <param name="filepath">
  94. /// The filepath where to save the serialized data.
  95. /// </param>
  96. ///
  97. /// <param name="format">
  98. /// The serialization format.
  99. /// </param>
  100. /// ----------------------------------------------------------------------------------------------------
  101. [DebuggerStepThrough()]
  102. [DebuggerHidden()]
  103. public static void Serialize<T>(T obj, string filepath, SerializationFormat format)
  104. {
  105. object serializer = SerializationUtil.GetSerializer<T>(format);
  106.  
  107. using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
  108.  
  109. switch (serializer.GetType) {
  110.  
  111. case typeof(BinaryFormatter):
  112. ((BinaryFormatter)serializer).Serialize(fs, obj);
  113.  
  114. break;
  115. case typeof(XmlSerializer):
  116. ((XmlSerializer)serializer).Serialize(fs, obj);
  117.  
  118. break;
  119. }
  120.  
  121. }
  122.  
  123. }
  124.  
  125. /// ----------------------------------------------------------------------------------------------------
  126. /// <summary>
  127. /// Deserializes the data of an Object from the specified file, using the specified deserialization format.
  128. /// </summary>
  129. /// ----------------------------------------------------------------------------------------------------
  130. /// <typeparam name="T">
  131. /// </typeparam>
  132. ///
  133. /// <param name="filepath">
  134. /// The filepath where from deserialize the serialized data.
  135. /// </param>
  136. ///
  137. /// <param name="format">
  138. /// The serialization format.
  139. /// </param>
  140. /// ----------------------------------------------------------------------------------------------------
  141. [DebuggerStepThrough()]
  142. [DebuggerHidden()]
  143. public static T Deserialize<T>(string filepath, SerializationFormat format)
  144. {
  145.  
  146. object serializer = SerializationUtil.GetSerializer<T>(format);
  147.  
  148. using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
  149.  
  150. switch (serializer.GetType) {
  151.  
  152. case typeof(BinaryFormatter):
  153.  
  154. return (T)((BinaryFormatter)serializer).Deserialize(fs);
  155. case typeof(XmlSerializer):
  156.  
  157. return (T)((XmlSerializer)serializer).Deserialize(fs);
  158. }
  159.  
  160. }
  161.  
  162. }
  163.  
  164. /// ----------------------------------------------------------------------------------------------------
  165. /// <summary>
  166. /// Deserializes the data of an Object from the specified file, using the specified deserialization format.
  167. /// </summary>
  168. /// ----------------------------------------------------------------------------------------------------
  169. /// <typeparam name="T">
  170. /// </typeparam>
  171. ///
  172. /// <param name="filepath">
  173. /// The filepath where from deserialize the serialized data.
  174. /// </param>
  175. ///
  176. /// <param name="format">
  177. /// The serialization format.
  178. /// </param>
  179. /// ----------------------------------------------------------------------------------------------------
  180. [DebuggerStepThrough()]
  181. [DebuggerHidden()]
  182. public static void Deserialize<T>(ref T refObj, string filepath, SerializationFormat format)
  183. {
  184. refObj = SerializationUtil.Deserialize<T>(filepath, format);
  185.  
  186. }
  187.  
  188. #endregion
  189.  
  190. }
  191.  
  192. //=======================================================
  193. //Service provided by Telerik (www.telerik.com)
  194. //=======================================================

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7.  
  8. public sealed class Form1 : Form
  9. {
  10.  
  11. private void Form1_Load()
  12. {
  13. Test();
  14. }
  15.  
  16.  
  17. private void Test()
  18. {
  19. string filePath = "C:\\file.dat";
  20.  
  21. Contact currentContact = GetContact(filePath);
  22.  
  23. Console.WriteLine(string.Format("Name...: {0}", currentContact.Name));
  24. Console.WriteLine(string.Format("Surname: {0}", currentContact.Surname));
  25.  
  26. currentContact.Name = "Pepito";
  27. currentContact.Surname = "Palotes";
  28.  
  29. this.SetContact("C:\\file.dat", currentContact);
  30.  
  31. }
  32.  
  33. private Contact GetContact(string filePath)
  34. {
  35.  
  36. return SerializationUtil.Deserialize<Contact>(filePath, SerializationFormat.Binary);
  37.  
  38. }
  39.  
  40.  
  41. private void SetContact(string filepath, Contact contact)
  42. {
  43. SerializationUtil.Serialize(contact, filepath, SerializationFormat.Binary);
  44.  
  45. }
  46. public Form1()
  47. {
  48. Shown += Form1_Load;
  49. }
  50.  
  51. }

Código
  1. [Serializable()]
  2. public sealed class Contact
  3. {
  4.  
  5. public string Name { get; set; }
  6. public string Surname { get; set; }
  7.  
  8. }
  9.  
  10. //=======================================================
  11. //Service provided by Telerik (www.telerik.com)
  12. //=======================================================
  13.  

EDITO:
Ejemplo al utilizar la serialización XML:
Código
  1. <?xml version="1.0"?>
  2. <Contact xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3.  <Name>Pepito</Name>
  4.  <Surname>Palotes</Surname>
  5. </Contact>

Saludos.
« Última modificación: 5 Septiembre 2015, 16:26 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
Agregar lineas de texto a un archivo « 1 2 »
Dudas Generales
Paco_Colombia 11 18,072 Último mensaje 11 Marzo 2013, 13:07 pm
por Cracker_novato
Editar y modificar archivos de texto desde php « 1 2 »
PHP
drakolive 13 11,237 Último mensaje 4 Agosto 2007, 04:12 am
por yeikos
[PHP] Abrir txt y agregar líneas al final del texto
PHP
Brian1511 0 2,405 Último mensaje 24 Noviembre 2015, 04:28 am
por Brian1511
Recorrer líneas de texto en un QTextEdit (Python+QtDesigner/Pyside)
Scripting
curiosport 3 3,497 Último mensaje 26 Febrero 2016, 00:08 am
por curiosport
ayuda, necesito un comando para editar lineas de texto
Criptografía
S3rg!o 3 3,141 Último mensaje 5 Diciembre 2017, 23:45 pm
por El_Andaluz
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines