Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 22 Noviembre 2015, 10:23 am



Título: Generar un archivo txt con fecha hora y una variable
Publicado por: Meta en 22 Noviembre 2015, 10:23 am
Hola:

Uso Visual Studio Community 2015 en español. ;)

Teniendo un formulador Form con C#,incluyo dos botones y un richTextBox, en el cual en el botón 1 si lo pulso, me indica en el richTextBox la fecha y hora y un valor de una variable tipo string que dice "Esto es una prueba".

El el segundo botón, solo genera un archivo txt y en el archiv de texto creado indica en su interior la fecha, hora y el valor de la variable string que comenté arriba.

¿Cómo se hace?

La manera como lo he hecho hasta ahora no es la adecuada, es esta:

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.IO; // No olvidar.
  12.  
  13. namespace Generar_txt
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        // Variable.
  23.        string Variable = "Esto es una prueba ";
  24.  
  25.        string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  26.  
  27.  
  28.  
  29.        private void button1_Click(object sender, EventArgs e)
  30.        {
  31.            richTextBox1.Text = Variable + contenido;
  32.        }
  33.  
  34.        private void button2_Click(object sender, EventArgs e)
  35.        {
  36.            // File.WriteAllText(@"c:\carpeta\nombrearch.txt", VAriable + contenido);
  37.            File.WriteAllText(@"nombrearch.txt", Variable + contenido);
  38.        }
  39.    }
  40. }
  41.  
  42.  

Da este error porque no crea una carpeta o directorio.
(https://social.msdn.microsoft.com/Forums/getfile/749230)

Si usar carpeta si funciona, por si acaso, quiero usar carpeta, ejjejejje.

Otra cosa, cada vez que pulso el botón 2 varias veces, como que se borra lo anterior y se queda lo nuevo.

 ¿Se puede hacer de alguna manera que se vea poco a poco los datos actualizado sin que se borre nada?

En cada mes quiero que genere un archivo .txt automáticamente, que se llame así por cada archivo: Archivo 22-11-2015.txt.

Saludos.


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Lekim en 22 Noviembre 2015, 15:27 pm
Hola

  Te da error  porque el directorio no existe . Primero debes crear el directorio:

Código
  1. Directory.CreateDirectory(MyDir)

Para añadir texto a un archivo ya creado debes usar AppendAllText (si no hay archivo lo crea):

Código
  1. File.AppendAllText(FilePath, ContentFile)

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.IO;
  11. namespace WindowsFormsApplication1
  12. {
  13.    public partial class Form1 : Form
  14.    {
  15.        public Form1()
  16.        {
  17.            InitializeComponent();
  18.        }
  19.        // Variable.    
  20.        string Variable = "Esto es una prueba ";        
  21.        string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  22.        private void Form1_Load(object sender, EventArgs e)
  23.        {
  24.  
  25.        }
  26.  
  27.        private void button1_Click(object sender, EventArgs e)
  28.        {
  29.            richTextBox1.Text = Variable + contenido;
  30.        }
  31.  
  32.        private void button2_Click(object sender, EventArgs e)        
  33.        {   string sDirectory = @"C:\Carpeta";
  34.            string NameFile = "NombreArchivo.txt";
  35.            string FilePath = string.Format("{0}\\{1}", sDirectory, NameFile);
  36.            string sAddLine = string.Format("{0}{1}{2}", Variable, contenido, Environment.NewLine);
  37.  
  38.            //Si el directorio no existe entonces lo crea
  39.            if (Directory.Exists(sDirectory).Equals(false))
  40.            {
  41.                Directory.CreateDirectory(sDirectory);
  42.            }        
  43.            //Escribe en el archivo      
  44.            File.AppendAllText(FilePath, sAddLine);
  45.            //File.WriteAllText(String.Format("{0}\\{1}", sDirectory, NameFile), Variable + contenido)
  46.            //File.WriteAllText("nombrearch.txt", Variable & contenido)
  47.        }      
  48.    }    
  49. }
  50.  







Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Meta en 22 Noviembre 2015, 22:21 pm
Hola:

Le he cambiado el nombre de las variables proque me gusta más.

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.IO; // No olvidar.
  12.  
  13. namespace Generar_txt
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        // Variable.
  23.        string Variable = "Esto es una prueba ";
  24.        string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  25.  
  26.        private void button1_Click(object sender, EventArgs e)
  27.        {
  28.            richTextBox1.Text = Variable + contenido;
  29.        }
  30.  
  31.        private void button2_Click(object sender, EventArgs e)
  32.        {
  33.            string Directorio = @"C:\Carpeta";
  34.            string Nombre_del_Archivo = "Archivo_de_Ulises.txt";
  35.            string Archivo_Path = string.Format("{0}\\{1}", Directorio, Nombre_del_Archivo);
  36.            string Agregar_Linea = string.Format("{0}{1}{2}", Variable, contenido, Environment.NewLine);
  37.  
  38.            //Si el directorio no existe entonces lo crea
  39.            if (Directory.Exists(Directorio).Equals(false))
  40.            {
  41.                Directory.CreateDirectory(Directorio);
  42.            }
  43.            //Escribe en el archivo      
  44.            File.AppendAllText(Archivo_Path, Agregar_Linea);
  45.            richTextBox1.Text += Variable + contenido + "\r\n";
  46.        }
  47.    }
  48. }

Funciona todo a la primera.

Muchísimas gracias mi muy distinguido amigo. ;)


Edito:

Ahora lo hice con el timer en 600000 ms, lo que equivale a 10 minutos, activo el timer con un botón pero hay un problema, que la hora nunca cambia.

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.IO; // No olvidar.
  12.  
  13. namespace Generar_txt
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        // Variable.
  23.        string Variable = "Esto es una prueba ";
  24.        string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  25.  
  26.        private void button1_Click(object sender, EventArgs e)
  27.        {
  28.            richTextBox1.Text = Variable + contenido;
  29.        }
  30.  
  31.        private void button2_Click(object sender, EventArgs e)
  32.        {
  33.            timer1.Enabled = true;
  34.        }
  35.  
  36.        private void timer1_Tick(object sender, EventArgs e)
  37.        {
  38.            string Directorio = @"C:\Carpeta";
  39.            string Nombre_del_Archivo = "Archivo_de_Ulises.txt";
  40.            string Archivo_Path = string.Format("{0}\\{1}", Directorio, Nombre_del_Archivo);
  41.            string Agregar_Linea = string.Format("{0}{1}{2}", Variable, contenido, Environment.NewLine);
  42.  
  43.            //Si el directorio no existe entonces lo crea
  44.            if (Directory.Exists(Directorio).Equals(false))
  45.            {
  46.                Directory.CreateDirectory(Directorio);
  47.            }
  48.            //Escribe en el archivo      
  49.            File.AppendAllText(Archivo_Path, Agregar_Linea);
  50.            richTextBox1.Text += Variable + contenido + "\r\n";
  51.        }
  52.    }
  53. }
  54.  

¿Algún problema?

Saludos.


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Eleкtro en 23 Noviembre 2015, 11:50 am
hay un problema, que la hora nunca cambia.

El problema es que a la variable contenido solo le asignas el valor (la fecha/hora) una única vez...

Tienes que actualizar la variable (fecha/hora) en cada tick, dentro del bloque del handler timer1_Tick.

Saludos


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Meta en 23 Noviembre 2015, 15:17 pm
Hola:

Tengo que poner en el timer lo que dijiste, me imagino que será todo esto.
Código
  1. string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);

Sigo investigando.

Gracias.


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Eleкtro en 23 Noviembre 2015, 15:28 pm
me imagino que será todo esto.
Código
  1. string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);

La variable ya la tienes declarada fuera del método (this.contenido = ...), pero si lo prefieres también puedes hacerlo cómo has expuesto ...declarando dicha variable en cada tick.

Saludos


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Meta en 24 Noviembre 2015, 00:33 am
Hola:

Parece ser que así si funciona.
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. using System.IO; // No olvidar.
  12.  
  13. namespace Generar_txt
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        // Variable.
  23.        string Variable = "Esto es una prueba ";
  24.  
  25.        private void button1_Click(object sender, EventArgs e)
  26.        {
  27.            // richTextBox1.Text = Variable + contenido;
  28.        }
  29.  
  30.        private void button2_Click(object sender, EventArgs e)
  31.        {
  32.            timer1.Enabled = true;
  33.        }
  34.  
  35.        private void timer1_Tick(object sender, EventArgs e)
  36.        {
  37.            string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  38.            string Directorio = @"C:\Carpeta";
  39.            string Nombre_del_Archivo = "Archivo_de_Ulises.txt";
  40.            string Archivo_Path = string.Format("{0}\\{1}", Directorio, Nombre_del_Archivo);
  41.            string Agregar_Linea = string.Format("{0}{1}{2}", Variable, contenido, Environment.NewLine);
  42.  
  43.  
  44.            //Si el directorio no existe entonces lo crea
  45.            if (Directory.Exists(Directorio).Equals(false))
  46.            {
  47.                Directory.CreateDirectory(Directorio);
  48.            }
  49.            //Escribe en el archivo      
  50.            File.AppendAllText(Archivo_Path, Agregar_Linea);
  51.            richTextBox1.Text += Variable + contenido + "\r\n";
  52.        }
  53.    }
  54. }

Siguiendo con el proyecto. Solo teniendo en el Form1 el richTextBox. En este caso recibo datos en el puerto serie. Cada 600000 ms que son cada 10 minutos, guarda en el txt los datos recibidos del puerto serie y añade la fecha y hora al lado.

Código
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.IO.Ports;
  7. // No olvidar.
  8. using System.Text;
  9. // No olvidar.
  10. using System.IO;
  11. // No olvidar.
  12.  
  13. public class Form1
  14. {
  15. // Utilizaremos un string como buffer de recepción.
  16.  
  17. string Recibidos;
  18. public Form1()
  19. {
  20. FormClosing += Form_Principal_FormClosing;
  21. InitializeComponent();
  22. // Abrir puerto mientras se ejecuta la aplicación.
  23. if (!SerialPort1.IsOpen) {
  24. try {
  25. SerialPort1.Open();
  26. } catch (System.Exception ex) {
  27. MessageBox.Show(ex.ToString());
  28. }
  29. }
  30.  
  31. // Ejecutar la función Recepcion por disparo del Evento 'DataReived'.
  32. SerialPort1.DataReceived += Recepcion;
  33.  
  34. }
  35.  
  36. // Al recibir datos.
  37. private void Recepcion(object sender, SerialDataReceivedEventArgs e)
  38. {
  39. // Acumular los caracteres recibidos a nuestro 'buffer' (string).
  40. Recibidos += SerialPort1.ReadExisting();
  41. // Invocar o llamar al proceso de tramas.
  42. this.Invoke(new EventHandler(Actualizar));
  43. }
  44.  
  45. // Procesador los datos recibidos en el buffer y extraer tramas copletas.
  46. private void Actualizar(object s, EventArgs e)
  47. {
  48. // Asignar el valor de la trama textBox.
  49. RichTextBox1.Text = Recibidos;
  50.  
  51. // Selecciona la posición final para leer los mensajes entrantes.
  52. RichTextBox1.SelectionStart = RichTextBox1.Text.Length;
  53.  
  54. // Mantiene el scroll en la entrada de cada mensaje.
  55. RichTextBox1.ScrollToCaret();
  56. }
  57.  
  58. // Si cierras el programa.
  59. private void Form_Principal_FormClosing(object sender, FormClosingEventArgs e)
  60. {
  61. // ¿El puerto está abierto?
  62. if (!SerialPort1.IsOpen) {
  63. SerialPort1.Close();
  64. // Cierra el ppuerto.
  65. }
  66. }
  67.  
  68. private void Timer1_Tick(object sender, EventArgs e)
  69. {
  70. string contenido = string.Format("{0:dd/MM/yyyy HH:mm} ", DateTime.Now);
  71. string Directorio = "C:\\Carpeta_VB";
  72. string Nombre_del_Archivo = "Archivo_de_Ulises.txt";
  73. string Archivo_Path = string.Format("{0}\\{1}", Directorio, Nombre_del_Archivo);
  74. string Agregar_Linea = string.Format("{0}{1}{2}", Recibidos, contenido, Environment.NewLine);
  75.  
  76. //Si el directorio no existe entonces lo crea
  77. if (Directory.Exists(Directorio).Equals(false)) {
  78. Directory.CreateDirectory(Directorio);
  79. }
  80. //Escribe en el archivo      
  81. File.AppendAllText(Archivo_Path, Agregar_Linea);
  82. RichTextBox1.Text += Recibidos + contenido + Constants.vbCr + Constants.vbLf;
  83. Recibidos = "";
  84. }
  85. }

El problema que no me sale los datos junto con la fecha.

Lo ideal es hacer el programa que guarde los datos recibidos en la variable "Recibidos", más la "fecha y hora" en el richTextBox luego por cada 10 minutos, se guarda en el txt gracias al timer1.

No me sale como quiero. ¿Qué es lo que falla?

Saludos.


Título: Re: Generar un archivo txt con fecha hora y una variable
Publicado por: Eleкtro en 24 Noviembre 2015, 18:33 pm
El problema que no me sale los datos junto con la fecha.

No me sale como quiero. ¿Qué es lo que falla?

1. ¿Antes de escribir en el control y en el archivo local, has comprobado que el string Recibidos no está vacío?, ¿o qué significa "No me sale como quiero"?.

De todas formas, tema aparte, tienes un lio de nombres de objetos ahí montado, yo te sugiero dejarlo así:

Código
  1. internal SerialPort SP = new SerialPort(...);
  2. private string dataIn;
  3.  
  4. private void Recepcion(object sender, SerialDataReceivedEventArgs e)
  5. {
  6. // ...
  7. dataIn += SP.ReadExisting();
  8. // ...
  9. }
  10.  
  11. private void Timer1_Tick(object sender, EventArgs e)
  12. {
  13. string dirpath = "C:\\Carpeta_VB";
  14. string filepath = Path.Combine(dirpath, "Archivo_de_Ulises.txt");
  15. string dataOut = string.Format("{0}{1:dd/MM/yyyy HH:mm}{2}",
  16.                                       this.dataIn, DateTime.Now.ToString, Environment.NewLine);
  17.        this.dataIn = "";
  18.  
  19. if (!Directory.Exists(dirpath)) {
  20. Directory.CreateDirectory(dirpath);
  21. }
  22.  
  23. this.RichTextBox1.AppendText(dataOut);
  24. File.AppendAllText(filepath, dataOut);
  25. }
  26.  
  27. //=======================================================
  28. //Service provided by Telerik (www.telerik.com)
  29. //=======================================================

saludos