【问题标题】:How to make use of memorystream instead of filestream如何使用内存流而不是文件流
【发布时间】:2026-02-12 13:20:03
【问题描述】:

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

我从程序中读取并保存到 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;
}

控制器代码:

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

【问题讨论】:

    标签: c# asp.net-mvc serialization memorystream


    【解决方案1】:

    你可以这样:

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

    【讨论】:

    • 我得到一个例外说:System.ObjectDisposedException:无法访问关闭的流。
    • 然后尝试使用字节,不知道为什么会发生。我更新了代码以使用字节来传递结果。
    • 工作!非常感谢。当它允许我时会批准答案
    【解决方案2】:

    我建议您彻底分离关注点,因为您也在使用 Asp.Net MVC。与其在同一个方法中读取和创建内存流,不如先读取/获取您需要的数据集合,然后从方法中返回数据。然后在 action 方法中,您可以根据您的要求使用所需的格式(绑定到 UI 或返回文件等)来装饰它

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

    希望对您有所帮助。

    【讨论】:

    • 你是对的。我会照你说的做,把代码拆分成多个方法,这样就很容易找出所有东西的位置。谢谢你的提示,我很感激。
    【解决方案3】:
            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
            }
    

    【讨论】:

      最近更新 更多