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

前端 未结 7 1208
隐瞒了意图╮
隐瞒了意图╮ 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 00:52

    I came up with this, it's a better CSV writer than the other answers:

    public static class DataReaderExtension
    {
        public static void ToCsv(this IDataReader dataReader, string fileName, bool includeHeaderAsFirstRow)
        {
    
            const string Separator = ",";
    
            StreamWriter streamWriter = new StreamWriter(fileName);
    
            StringBuilder sb = null;
    
            if (includeHeaderAsFirstRow)
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount; index++)
                {
                    if (dataReader.GetName(index) != null)
                        sb.Append(dataReader.GetName(index));
    
                    if (index < dataReader.FieldCount - 1)
                        sb.Append(Separator);
                }
                streamWriter.WriteLine(sb.ToString());
            }
    
            while (dataReader.Read())
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount; index++)
                {
                    if (!dataReader.IsDBNull(index))
                    {
                        string value = dataReader.GetValue(index).ToString();
                        if (dataReader.GetFieldType(index) == typeof(String))
                        {
                            if (value.IndexOf("\"") >= 0)
                                value = value.Replace("\"", "\"\"");
    
                            if (value.IndexOf(Separator) >= 0)
                                value = "\"" + value + "\"";
                        }
                        sb.Append(value);
                    }
    
                    if (index < dataReader.FieldCount - 1)
                        sb.Append(Separator);
                }
    
                if (!dataReader.IsDBNull(dataReader.FieldCount - 1))
                    sb.Append(dataReader.GetValue(dataReader.FieldCount - 1).ToString().Replace(Separator, " "));
    
                streamWriter.WriteLine(sb.ToString());
            }
            dataReader.Close();
            streamWriter.Close();
        }
    }
    

    usage: mydataReader.ToCsv("myfile.csv", true)

提交回复
热议问题