写入CSV文件,并出口吗? [英] Write to CSV file and export it?

查看:235
本文介绍了写入CSV文件,并出口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中ASP.net,可能会有人告诉我,我怎么能写从阵列/列表条目到服务器上的一个CSV文件,然后打开该文件?我认为第二个部分是类似 - 的Response.Redirect(http://myserver.com/file.csv),但对如何写服务器上的文件不知道

In C# ASP.net, could someone show me how I can write entries from an Array/List to a CSV file on the server and then open the file? I think the second part would be something like - Response.Redirect("http://myserver.com/file.csv"), however not sure on how to write the file on the server.

此外,如果这个页面是由许多用户访问,是它更好地生成一个新的CSV文件,每次或覆盖相同的文件?会不会有任何读/写/锁定问题,如果两个用户试图访问相同的CSV文件等。

Also if this page is accessed by many users, is it better to generate a new CSV file every time or overwrite the same file? Would there be any read/write/lock issues if both users try accessing the same CSV file etc.?

更新:

这可能是一个愚蠢的问题,我已经搜索在谷歌,但我无法找到一个明确的答案 - 你怎么写一个CSV文件到网络服务器和出口在C#中ASP.net?我知道如何产生的,但我想救它www.mysite.com/my.csv~~V,然后导出它。

This is probably a silly question and I have searched on Google but I'm not able to find a definitive answer - how do you write a CSV file to the webserver and export it in C# ASP.net? I know how to generate it but I would like to save it to www.mysite.com/my.csv and then export it.

推荐答案

罗,你这样做是错误的。你不希望将文件写入磁盘,以便IIS可以为他们服务的。这增加了安全隐患,以及增加了复杂性。你真正需要做的是直接保存CSV响应流。

Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.

下面的情况:用户希望下载CSV。用户提交表单有关他们想要的CSV细节。您prepare的CSV文件,然后可以用于构造csv文件并将其写入响应流的aspx页面提供给用户的URL。用户点击该链接。 ASPX页面是空白的;在页面codebehind您只需编写CSV响应流,并结束它。

Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.

您可以添加以下的(我相信这是正确的)的负载事件:

You can add the following to the (I believe this is correct) Load event:

string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");

var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
  sb.AppendLine(TransformDataLineIntoCsv(line));

HttpContext.Current.Response.Write(sb.ToString());

写作从这里 ganked响应流code

writing to the response stream code ganked from here.

这篇关于写入CSV文件,并出口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆