Created
July 25, 2015 12:49
-
-
Save Fhernd/b370ef5a7633b8602fa7 to your computer and use it in GitHub Desktop.
Demostración de uso del método File.WriteAllLines en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
namespace Receta.CSharp.R0524 | |
{ | |
public class UsoWriteAllLines | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine(Environment.NewLine); | |
// Archivo en directorio actual para escritura de | |
// registro de eventos: | |
string archivo = "log.txt"; | |
// Arreglo de objetos `string` con los datos | |
// del registro de eventos de la aplicación: | |
string[] eventos = new string[5]; | |
// Agrega la hora de inicio de la aplicación: | |
eventos[0] = String.Format("Tiempo inicio aplicación: {0}", DateTime.Now.ToString()); | |
try | |
{ | |
throw new Exception(); | |
} | |
catch(Exception e) | |
{ | |
eventos[1] = String.Format("Se produjo una excepción: {0}", e.Message); | |
} | |
// Escritura de los eventos de registro: | |
File.WriteAllLines(archivo, eventos); | |
// Adiciona un registro estra al mismo archivo: | |
string tiempoFin = String.Format("Tiempo fin aplicación: {0}", DateTime.Now.ToString()); | |
File.AppendAllText(archivo, tiempoFin); | |
// Muestra el contenido del contenido del archivo | |
// de registro: | |
string[] registros = File.ReadAllLines(archivo); | |
foreach( string registro in registros) | |
{ | |
// Omite registros sin contenido: | |
if(registro.Equals(String.Empty)) | |
{ | |
continue; | |
} | |
Console.WriteLine (registro); | |
} | |
Console.WriteLine(Environment.NewLine); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment