【发布时间】: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
【问题讨论】:
标签: c# asp.net-mvc serialization memorystream