简体   繁体   English

如何使用内存流代替文件流

[英]How to make use of memorystream instead of filestream

So what im trying to do is read a Select store procedure from my database save the data in a csv file and make it that the user is able to download it through the web application. 因此,我想做的就是从我的数据库中读取Select存储过程,将数据保存在csv文件中,并确保用户可以通过Web应用程序下载数据。 I was able to get the requested result by saving the file temporary into my program foldel and using filestream. 通过将文件临时保存到程序文件夹中并使用文件流,可以得到请求的结果。 What i want to do now is skip the part where the file is saved onto my computer and temporary save it in the RAM memory instead. 我现在想做的是跳过将文件保存到计算机上的部分,并将其临时保存到RAM内存中。 From what i understood i have to make use of memory stream instead of file stream but i dont really understand how i can do that. 据我了解,我必须利用内存流而不是文件流,但是我真的不明白我该怎么做。 From what i understood from what i read is that instead of me making use of a file i need to convert my data to bytes make a memorystream out of it and then use it in my FileStreamResult. 据我了解,我不是使用文件而是将数据转换为字节,而是将数据转换为字节,然后在FileStreamResult中使用它。 Am i correct here? 我在这里正确吗?

Method when i read from procedure and save to a csvfile: 当我从过程中读取并保存到csvfile时的方法:

public static String StoreApproved ()
{          
    string path1 = HttpRuntime.AppDomainAppPath + "Report.csv";
    SqlConnection sqlConnection1 = new SqlConnection("CONNECTIONSTRING");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader reader;
    cmd.CommandText = "ExportApproved";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = sqlConnection1;
    sqlConnection1.Open();
    reader = cmd.ExecuteReader();
    List<ModelStoreProcedureApproved> TestList = new List<ModelStoreProcedureApproved>();
    ModelStoreProcedureApproved test ;

    while (reader.Read())
    {
        test = new ModelStoreProcedureApproved();
       // test.Id = int.Parse(reader["IdTimeTracker"].ToString());
        test.Month = reader["Month"].ToString();
        test.EmailUser = reader["Email"].ToString();
        test.Project = reader["Name"].ToString();
        test.Approved = reader["Description"].ToString();
        test.Month = reader["Month"].ToString();
        test.Year = reader["Year"].ToString();
        TestList.Add(test);
    }

    File.Create(path1).Close();
    var i = TestList.FirstOrDefault();
    using (TextWriter fileReader = new StreamWriter(path1))
    {
        var csv = new CsvWriter(fileReader);
        csv.Configuration.Encoding = Encoding.UTF8;
        foreach (var value in TestList)
        {
            csv.WriteRecord(value);
        }
        fileReader.Close();
    }
    sqlConnection1.Close();
    return path1;
}

Controller code: 控制器代码:

public ActionResult ExportToCSV()
{
    string path = Repositories.UserRepository.StoreApproved();
    var fileStream = new FileStream(path,
                                    FileMode.Open,
                                    FileAccess.Read);

    return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = "export.csv" };
}

Can someone explain me what the best way to do this is? 有人可以告诉我最好的方法是什么吗? Other posts i have read Serialize and Deserialize using BinaryFormatter 我已阅读其他使用BinaryFormatter进行序列化和反序列化的帖子

BinaryFormatter and Deserialization Complex objects BinaryFormatter和反序列化复杂对象

Using CSVHelper to output stream to browser 使用CSVHelper将流输出到浏览器

You can make it like this: 您可以这样:

public static byte[] StoreApproved ()
{          
    string path1 = HttpRuntime.AppDomainAppPath + "Report.csv";
    SqlConnection sqlConnection1 = new SqlConnection("CONNECTIONSTRING");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader reader;
    cmd.CommandText = "ExportApproved";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = sqlConnection1;
    sqlConnection1.Open();
    reader = cmd.ExecuteReader();
    List<ModelStoreProcedureApproved> TestList = new List<ModelStoreProcedureApproved>();
    ModelStoreProcedureApproved test ;

    while (reader.Read())
    {
        test = new ModelStoreProcedureApproved();
       // test.Id = int.Parse(reader["IdTimeTracker"].ToString());
        test.Month = reader["Month"].ToString();
        test.EmailUser = reader["Email"].ToString();
        test.Project = reader["Name"].ToString();
        test.Approved = reader["Description"].ToString();
        test.Month = reader["Month"].ToString();
        test.Year = reader["Year"].ToString();
        TestList.Add(test);
    }

    var i = TestList.FirstOrDefault();
    var mem = new MemoryStream();
    using (TextWriter fileReader = new StreamWriter(mem))
    {
        var csv = new CsvWriter(fileReader);
        csv.Configuration.Encoding = Encoding.UTF8;
        foreach (var value in TestList)
        {
            csv.WriteRecord(value);
        }
    }
    sqlConnection1.Close();
    return mem.ToArray();
}

public ActionResult ExportToCSV()
{
    byte[] bytes = Repositories.UserRepository.StoreApproved();
    Stream stream = new MemoryStream(bytes);
    return new FileStreamResult(stream, "text/csv") { FileDownloadName = "export.csv" };
}

I suggest you make clean separation of concerns since you are also using Asp.Net MVC. 由于您也使用Asp.Net MVC,因此建议您将关注点清晰地分开。 Instead of reading and creating memory stream inside same method, first read/get the data collection you need and just return the data out of the method. 与其在同一方法中读取和创建内存流,不如先读取/获取所需的数据集合,然后将数据从该方法中返回。 Then inside the action method you can decorate it with required format(binding to UI or returning a file etc.) based on your requirement 然后在action方法中,您可以根据需要用所需的格式(绑定到UI或返回文件等)装饰它

Though this is not be a straight answer to your question, and if all that you are looking for is using a memory stream, there are plenty of examples available to use for example as shown here and the answer you accepted etc. 尽管这不是您问题的直接答案,并且如果您要寻找的只是使用内存流,那么可以使用许多示例,例如此处显示的示例以及您接受的答案等。

Hope this help you. 希望这对您有所帮助。

        using (var ms = new MemoryStream())
        {
            using (var writer = new StreamWriter(ms))
            using (var csv = new CsvWriter(writer))
            {
                csv.WriteRecords({A list here});
            }
           ms.ToArray() // here is your actual data in memory stream
        }

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

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