Save data in txt by going through a select

1

I need to develop a program that stores the result of a select in two variables and saves the data in a txt and shows by console the iteration resulting from the urls

I could already get it to print correctly in the console, they could indicate how to save the result of the iteration in a txt, that for each line a url is written with a line break.

  namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string url1 = null;


                SqlConnection con = new SqlConnection("server=SQL2014;database=ventas;integrated security = true");
                string strSQL = "select  Numero,Terreno "+
                                "FROM datos";
                SqlCommand cmd = new SqlCommand(strSQL, con);
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                          while (reader.Read())
                {
                    string resultadoNumero = reader["Numero"].ToString();
                    string resultadoTerreno = reader["Terreno"].ToString();

     url1 = "http://ReportServer/Pages/ReportViewer.aspx?/Pedidos" + resultadoNumero + resultadoTerreno;


                    Console.WriteLine(url1);


                }
                reader.Close();
                con.Close();
               Console.ReadLine();
           }

        }
        }
    
asked by Sebastian 24.08.2017 в 21:11
source

1 answer

0

You should consider the following:

static void Main(string[] args)
{
    string url = null;
    string strSQL = "select  Numero, Terreno FROM datos";

    string rutaArchivo = @"C:\miArchivo.txt";
    StringBuilder builder = new StringBuilder();

    SqlConnection con = new SqlConnection("server=SQL2014;database=ventas;integrated security = true");
    SqlCommand cmd = new SqlCommand(strSQL, con);
    con.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        string resultadoNumero = reader["Numero"].ToString();
        string resultadoTerreno = reader["Terreno"].ToString();

        url = "http://ReportServer/Pages/ReportViewer.aspx?/Pedidos" + resultadoNumero + resultadoTerreno;

        Console.WriteLine(url);
        builder.Append(url).AppendLine();
    }

    reader.Close();
    con.Close();

    Console.WriteLine("Creando archivo");
    File.WriteAllText(rutaArchivo, builder.ToString());

    Console.ReadLine();
}

Where, the variable builder will store all the Urls that are built and with the File.WriteAllText method it will create (if it does not exist) the file and write all the text.

PD. Do not forget to make the necessary references.

Reference:

answered by 25.08.2017 / 02:29
source