How do I write in a text file?

2

Good, I am more or less new in c #, in access to data and others, and I need to go making a log of where my program goes until the end, to know by try catch and others how it works.

My question was, how can I make it write messages in lines of text I have tried this, and do not write.

public static void metodoblablabla(){

  file = new System.IO.StreamWriter("C:/ruta/log.txt");
  Hace cosas;
  Hace cosas;
  //:) perdón por no especificar, pero es innecesario en este caso.
  try{
    file.write("Ha llegado hasta linea X");
    file.close();
  }catch(Exception e){
    file.WriteLine(e.Message);
    file.close();
  }
    
asked by Aritzbn 20.09.2017 в 15:58
source

2 answers

1

To write to a file you can use File.WriteAllLines ()

        string path = ""C:/ruta/log.txt"";
        string texto = "Ha llegado hasta linea X";
        File.WriteAllLines(path, createText);

Even so as not to overwrite the content, if you want to add other text to the content of the file, you can use File.AppendAllLines () :

        string path = ""C:/ruta/log.txt"";
        string texto = "Ha llegado hasta linea X";
        File.AppendAllLines(path, new String[] { texto });

Another method to add text to a file is by using the class StreamWriter :

        string path = ""C:/ruta/log.txt"";
        string texto = "Ha llegado hasta linea X";

        using (StreamWriter writer = new StreamWriter(path))
        {
            writer.WriteLine(texto);
        }
    
answered by 20.09.2017 / 16:48
source
3

Use the File.WriteAllLines() method that is much easier to use and write each element of the array in a new line:

File.WriteAllLine("C:/ruta/log.txt", new String[]{ "Ha llegado hasta linea X" });
File.WriteAllLine("C:/ruta/log.txt", new String[]{ "Esto se escribira en otra linea" });
    
answered by 20.09.2017 в 16:01