如何使用内存流而不是文件流

How to make use of memorystream instead of filestream

所以我想做的是从我的数据库中读取一个 Select 存储过程,将数据保存在一个 csv 文件中,并使用户能够通过 Web 应用程序下载它。通过将文件临时保存到我的程序文件夹中并使用文件流,我能够获得请求的结果。我现在要做的是跳过将文件保存到我的计算机上的部分,并将其临时保存在 RAM 内存中。据我了解,我必须使用内存流而不是文件流,但我真的不明白我该怎么做。从我读到的内容来看,我需要将数据转换为字节,而不是使用文件,从中创建内存流,然后在我的 FileStreamResult 中使用它。我说得对吗?

当我从程序中读取并保存到 csv 文件时的方法:

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;
}

控制器代码:

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" };
}

谁能告诉我最好的方法是什么? 我读过的其他帖子 Serialize and Deserialize using BinaryFormatter

BinaryFormatter and Deserialization Complex objects

Using CSVHelper to output stream to browser

你可以这样做:

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" };
}

我建议您彻底分离关注点,因为您还使用 Asp.Net MVC。不是在同一方法中读取和创建内存流,而是首先 read/get 您需要的数据收集,然后 return 从方法中提取数据。然后在操作方法中,您可以根据您的要求

用所需的格式(绑定到 UI 或 returning 文件等)对其进行装饰

虽然这不是您问题的直接答案,并且如果您正在寻找的只是使用内存流,那么有很多示例可供使用,例如 here 和回答你接受等

希望对您有所帮助。

        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
        }