c# and CSVs

Oh hi didnt see you there…
Say since your hear, have you ever wondered “hey I wanna read this csv data into my c# program, but I don’t want to bother downloading the file.”.
If thats what your thinking, just take a look below friend, today I discuss how to do this exact task.

As always, you can find the finished program here:
https://rextester.com/WYCNA76267




Advantages to this approach can be reading each line from the file into a custom object model. From there you can apply LINQ statements to compare and manipulate the objects in a list or array. This strategy opens the doors wide open for implementations that can assist you in automatically processing files. More posts will to follow this one with examples.




    public class Program
    {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Net;
    using System.IO;
    using System.Security.Authentication;
    
        public static string GetCSV(string url)
        {
            const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
            const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
            ServicePointManager.SecurityProtocol = Tls12;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            string results = sr.ReadToEnd();
            sr.Close();

            return results;
        } 
        
        public static void Main(string[] args)
        {
            List<string> splitted = new List<string>();
            string fileList = GetCSV("https://support.geckoboard.com/hc/en-us/article_attachments/201195596/MailOrderBricksMarketingdata2014.csv");
            string[] tempStr;

            tempStr = fileList.Split(',');

            foreach (string item in tempStr)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    splitted.Add(item);
                    Console.WriteLine(item);
                }
            }
        }
    }
Ian Fogelman

Ian Fogelman

My name is Ian Fogelman. I like to develop data driven solutions with SQL Server, Python, .NET and predictive analytics.