简体   繁体   English

如何在ASP.NET中的网站中下载CSV文件

[英]How to download a CSV file in website in ASP.NET

In my website I am trying to download a CSV which comes from Yahoo. 在我的网站上,我尝试下载来自Yahoo的CSV。 It contains some data. 它包含一些数据。

I am using the code given below to download CSV. 我正在使用下面给出的代码下载CSV。

Problem: 问题:

I want to download and fetch all the data from Yahoo's CSV but the whole CSV is not getting created on my side. 我想从Yahoo的CSV下载并获取所有数据,但是整个CSV并没有在我这边创建。

Only some portion of the data is copied. 仅部分数据被复制。 So CSV is not downloaded with all its data. 因此,不会下载CSV及其所有数据。

I tried increasing the Buffer size but that didn't help 我尝试增加缓冲区的大小,但这没有帮助

Data in Yahoo's CSV is as shown in below screenshot. 雅虎CSV中的数据如下图所示。 This is the data I want to download 这是我要下载的数据

替代文字

Data that I get in created CSV, when I download the same Yahoo's CSV is as shown below. 当我下载相同的Yahoo CSV时,我在创建的CSV中获得的数据如下所示。

替代文字

Code I am using to download the CSV from Yahoo 我用来从Yahoo下载CSV的代码

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://download.finance.yahoo.com/d/quotes.csv?s=^DJI+^N225+^GSPC+^GDAXI+^FCHI+^HSI+^IXIC+^FTSE&f=l1d14n");
        HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
        Stream str = ws.GetResponseStream();
        inBuf = new Byte[10000000];
        int bytesToRead = Convert.ToInt32(inBuf.ToString().Length);

        int bytesRead=0;
        while(bytesToRead>0)
        {
            int n = str.Read(inBuf,bytesRead,bytesToRead);
            if(n==0)
            {
                break;
            }
            bytesRead += n;
            bytesToRead -= n;
        }
        FileStream fstr = new FileStream("C:\\VSS Working Folder\\20th Jan 11 NewHive\\NewHive\\CSV\\new.csv", FileMode.OpenOrCreate, FileAccess.Write);
        fstr.Write(inBuf,0,bytesRead);
        str.Close();
        fstr.Close();
        return "CSV Downloaded Successfully!";

What could be wrong? 有什么事吗

inBuf.ToString() gives you "System.Byte[]" and the length of that string is 13. So you are only saving 13 characters which will only give you 10274.52,"1/2 from the downloaded file. inBuf.ToString()为您提供“ System.Byte []”,该字符串的长度为13。因此,您只保存了13个字符,这从下载的文件中只能得到10274.52,"1/2

You can get the length using inBuf.Length . 您可以使用inBuf.Length获得长度。 Note that Length returns an int so you don't need to cast to an int. 请注意,Length返回一个int,因此您无需转换为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM