我在服务器上制作了CSV文件-如何让客户端下载此文件? [英] I made csv file on the server - how can I let the client download this file?
问题描述
我已经在服务器上制作了csv,如下所示:
I have made csv on the server like this:
string Expath = @"d:\A.csv";
protected void Button3_Click(object sender, EventArgs e)
{
FileStream FS = null;
StreamWriter SW = null;
try
{
FS = new FileStream(Expath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
SW = new StreamWriter(FS, Encoding.Default);
SW.WriteLine("Test");
SW.WriteLine("1,2,3,4,5");
}
catch { }
finally
{
if (SW != null)
{
SW.Close();
FS.Close();
}
}
}
将此文件放在服务器上的 d:
上是否正确?如果不在哪里,最好在下摆放下摆?
is it correct to make this file on d:
on the server? if not where is better to place hem?
客户端制作文件后如何下载文件?(asp.net C#)
how do to that the client can download this file after he made it? (asp.net C#)
推荐答案
您可以使用此代码将文件推送到浏览器.
You could use this code to push the file to browser.
private void PushToBrowser(string FilePath, byte[] Data)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = @"application/csv";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath));
HttpContext.Current.Response.OutputStream.Write(Data, 0, Data.Length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
File.Delete(FilePath);
}
您可以使用以下代码将文本数据转换为字节数组
You could use the following code to convert you text data to byte array
byte[] Data = File.ReadAllBytes(FilePath)
I won't recommended keeping generated files outside the web directory, even though its possible to write to a directory outside the web root in ASP.NET through impersonation, but its not at all recommended on production enviornment.
这篇关于我在服务器上制作了CSV文件-如何让客户端下载此文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!