Search code examples
c#.netfilestream

To download and convert csv file to Datatable


I have a requirement where i need to download a csv file from given url and then export the data from file to database.

Is there any way to download and convert the file directly to datatable rather than saving it to harddisk and then reading it to datatable.

Hope my question make some sense.

Thanks in advance


Solution

  • You can use StreamReader class to download csv without the need to save it locally:

    public string DownloadCSV(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest .GetResponse();
    
        StreamReader streamReader = new StreamReader(httpWebResponse .GetResponseStream());
        string results = streamReader.ReadToEnd();
        streamReader .Close();
    
        return results;
    }