Pass SQL query result to a TXT C # file

0

Currently I'm trying to write the result of a query in a txt file, the code I use is this one, but the query brings two columns and I only manage to write the first column.

 SqlCommand comando = new SqlCommand("Select x,m * from xxx", cn);
                        SqlDataReader leer;
                        leer = comando.ExecuteReader();
                        while (leer.Read() == true)
                        {
                            FileStream Query = new FileStream("C:/DatosQuery.txt", FileMode.Append, FileAccess.Write);
                            StreamWriter Escriba = new StreamWriter(Query);
                            Escriba.Write(leer[0].ToString());
                            Escriba.Write(leer[1].ToString());
                            Escriba.WriteLine();
                            Escriba.Flush();
                            Escriba.Close();
                        }    

I remain attentive to suggestions, greetings.

    
asked by thiagolope7 18.07.2018 в 19:17
source

1 answer

0

You should close the StreamWriter when you finish writing the file, ie outside the while and the creation before it.

 FileStream Query = new FileStream("C:/DatosQuery.txt", FileMode.Append, FileAccess.Write);
    StreamWriter Escriba = new StreamWriter(Query);
    SqlCommand comando = new SqlCommand("Select x,m * from xxx", cn);
    SqlDataReader leer;
    leer = comando.ExecuteReader();
    while (leer.Read())
    {              
      Escriba.Write(leer[0].ToString());
      Escriba.Write(leer[1].ToString());
      Escriba.WriteLine();
      Escriba.Flush();

    }    
Escriba.Close();
    
answered by 18.07.2018 / 19:22
source