How to efficiently write to file from SQL datareader in c#?

前端 未结 7 1239
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 00:14

I have a remote sql connection in C# that needs to execute a query and save its results to the users\'s local hard disk. There is a fairly large amount of data this thing ca

7条回答
  •  攒了一身酷
    2020-12-15 01:02

    You are on the right track yourself. Use a loop with while(myReader.Read(){...} and write each record to the text file inside the loop. The .NET framework and operating system will take care of flushing the buffers to disk in an efficient way.

    using(SqlConnection conn = new SqlConnection(connectionString))
    using(SqlCommand cmd = conn.CreateCommand())
    {
      conn.Open();
      cmd.CommandText = QueryLoader.ReadQueryFromFileWithBdateEdate(
        @"Resources\qrs\qryssysblo.q", newdate, newdate);
    
      using(SqlDataReader reader = cmd.ExecuteReader())
      using(StreamWriter writer = new StreamWriter("c:\temp\file.txt"))
      {
        while(reader.Read())
        {
          // Using Name and Phone as example columns.
          writer.WriteLine("Name: {0}, Phone : {1}", 
            reader["Name"], reader["Phone"]);
        }
      }
    }
    

提交回复
热议问题