简体   繁体   English

如何将大数据写入文件C#

[英]How to write large data into file c#

I have to write a large data (12L)records in a csv file.I am using Streamwriter, to write in file but after around 6L records it gives me outofmemory error. 我必须在csv文件中写入大数据(12L)记录。我正在使用Streamwriter,以写入文件,但在6L记录之后,它给了我内存不足的错误。

also I am writing this file on server directly, is there any way I can than download this on browser later? 我也直接在服务器上写这个文件,有什么办法比以后在浏览器上下载呢?

This is my code: searchResult.Entities=is a list of EntityObject 这是我的代码:searchResult.Entities =是EntityObject的列表

using (StreamWriter fs = new StreamWriter
(new FileStream("Temp.csv", FileMode.Create)))
                    {
                        AddText(fs, headerString.ToString());
                        foreach (var org in searchResult.Entities.ToList())
                        {
                            StringBuilder sb = new StringBuilder();

                            appendText(sb, org.Id);
                            appendText(sb, org.LeadNo.HasValue ? org.LeadNo.Value.ToString() : "");


                            fs.WriteLine(sb.ToString());

                           foreach (var activity in org.Activities)
                           {
                              var activityString = new StringBuilder();
                             activityString.Append(" , , , , , , , , , , , , , , , , , ,");

                               appendText(activityString, org.Id);
                                appendText(activityString, org.LeadNo.HasValue ? org.LeadNo.Value.ToString() : "");

                            fs.WriteLine(activityString.ToString());

                           }

                        }

Getting all results from database int the object only take 100ms, but writing in file is around 1minute for 6L records. 从数据库int获取所有结果仅需要100毫秒,但是对于6L记录,写入文件大约需要1分钟。

You may try not to access all the properties 您可以尝试不访问所有属性

foreach (var org in searchResult.Entities.ToList()) //Change this

but just the ones which you needed: 但是只是您需要的那些:

var toItrate = searchResult.Entities.Select(s => new { Id = s.Id, LeadNo = (s.LeadNo.HasValue ? s.LeadNo.Value : String.Empty) }).ToList();

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

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