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

前端 未结 7 1238
隐瞒了意图╮
隐瞒了意图╮ 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:03

    I agree that your best bet here would be to use a SqlDataReader. Something like this:

    StreamWriter YourWriter = new StreamWriter(@"c:\testfile.txt");
    SqlCommand YourCommand = new SqlCommand();
    SqlConnection YourConnection = new SqlConnection(YourConnectionString);
    YourCommand.Connection = YourConnection;
    YourCommand.CommandText = myQuery;
    
    YourConnection.Open();
    
    using (YourConnection)
    {
        using (SqlDataReader sdr = YourCommand.ExecuteReader())
            using (YourWriter)
            {
                while (sdr.Read())
                    YourWriter.WriteLine(sdr[0].ToString() + sdr[1].ToString() + ",");
    
            }
    }
    

    Mind you, in the while loop, you can write that line to the text file in any format you see fit with the column data from the SqlDataReader.

提交回复
热议问题