title: How to efficiently write to file from SQL datareader in c#?
body: <p>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 can return, so need to think of an efficient way of storing it. I've read before that first putting the whole result into memory and then writing it is not a good idea, so if someone could help, would be great!</p>
  
  <p>I am currently storing the sql result data into a DataTable, although I am thinking it could be better doing something in <code>while(myReader.Read(){...}</code>
  Below is the code that gets the results:</p>
  
  <pre><code>          DataTable t = new DataTable();
              string myQuery = QueryLoader.ReadQueryFromFileWithBdateEdate(@"Resources\qrs\qryssysblo.q", newdate, newdate);
              using (SqlDataAdapter a = new SqlDataAdapter(myQuery, sqlconn.myConnection))
              {
                  a.Fill(t);
              }
  
              var result = string.Empty;
      for(int i = 0; i &lt; t.Rows.Count; i++)
      {
          for (int j = 0; j &lt; t.Columns.Count; j++)
          {
              result += t.Rows[i][j] + ",";
          }
  
  
          result += "\r\n";
      }
  </code></pre>
  
  <p>So now I have this huge result string. And I have the datatable. There has to be a much better way of doing it?</p>
  
  <p>Thanks.</p>