简体   繁体   English

通过C#WCF REST Web服务作为MemoryStream构建和发送非常大的CSV数据集

[英]Building and sending very large CSV data-set over C# WCF REST Web Service as MemoryStream

This topic is related to the question here: 本主题与这里的问题有关:

How to send a CSV file using C# WCF RESTful (ie Web) Service? 如何使用C#WCF RESTful(即Web)服务发送CSV文件?

I was able to send a very small data set by utilizing the method discussed at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx , which explains how to utilize a "RAW" programming model to send the response -- I'm using the MemoryStream class. 通过使用http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx中讨论的方法,我能够发送非常小的数据集,其中说明了如何利用“ RAW”编程模型发送响应-我正在使用MemoryStream类。

public Stream ReturnCSVSample()
{
    string csv = "Hello, World\nGoodBye, For, Now\n";
    byte[] csvBytes = Encoding.UTF8.GetBytes(csv);

    WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv";

    return new MemoryStream(csvBytes);
}

This works fine. 这很好。 However, in reality, I'm retrieving about 144,000 records from a SQL database table, two columns wide, and using string concatenation to format it into CSV. 但是,实际上,我要从一个SQL数据库表中检索大约144,000条记录,该表宽两列,并使用字符串连接将其格式化为CSV。 Then, I take this string,encode it as a bytes array and return it as a MemoryStream object. 然后,我将这个字符串编码为一个字节数组,并将其作为MemoryStream对象返回。 I let the service run for over 20 minutes and it still does not finish! 我让该服务运行了20分钟以上,但仍然无法完成! I've determined the bottleneck is the string concatenation. 我确定了瓶颈是字符串串联。 Why? 为什么? Because I performed the operation of retrieving these 144,000 records and storing it to a class I created and it took a few minutes, at most, to complete. 因为我执行了检索这144,000条记录并将其存储到我创建的类中的操作,所以最多只花了几分钟就完成了。

Either a string that large is inefficient or there is a better method to perform string concatenation for the amount of records I specified. 太大的字符串效率低下,或者有更好的方法对我指定的记录数量执行字符串连接。

How can I send a CSV stream over a web service with such as a large data set? 如何通过具有大量数据集的Web服务发送CSV流?

Thank you. 谢谢。

A StreamWriter() would do a better job than string concatenation: 与字符串连接相比, StreamWriter()会做得更好:

public Stream LoadStreamSample(Stream ms)
{
    using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8)){
        // Call SQL and iterate over rows from SqlDataReader here...
        while (dr.Read()){
            // replace following with csv of one record
            string csv = "Hello, World\nGoodBye, For, Now\n";
            sw.WriteLine(csv)
        }
    }
    return ms;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM