SHARE
TWEET

Untitled

a guest Sep 16th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class CsvReader : IEnumerable
  2. {
  3.     IEnumerator _enumerator;
  4.  
  5.     public CsvReader(string path, string headerToReturn)
  6.     {
  7.         _enumerator = new CsvEnumerator(path, headerToReturn);
  8.     }
  9.  
  10.     public IEnumerator GetEnumerator()
  11.     {
  12.         return _enumerator;
  13.     }
  14.  
  15.  
  16.     static void Main(string[] args)
  17.     {
  18.         CsvReader csvReader = new CsvReader("imdb.csv", "URL");
  19.  
  20.         foreach (string s in csvReader)
  21.         {
  22.             Console.WriteLine(s);
  23.         }
  24.  
  25.         Console.WriteLine();
  26.     }
  27. }
  28.  
  29. class CsvEnumerator : IEnumerator
  30. {
  31.     private FileStream fs;
  32.     private StreamReader sr;
  33.     private string line, headerToReturn;
  34.     private char delimiter = ',';
  35.     private int headerPosition = -1;
  36.        
  37.     public CsvEnumerator(string path, string headerToReturn)
  38.     {
  39.         this.headerToReturn = headerToReturn;
  40.  
  41.         fs = File.OpenRead(path);
  42.  
  43.         if (!fs.CanRead)
  44.             throw new IOException("File cannot be read: " + path);
  45.  
  46.         sr = new StreamReader(fs);
  47.  
  48.         if (headerToReturn == null)
  49.         {
  50.             Console.WriteLine("Warning!: Header not specified. Returning all of the text.");
  51.             return;
  52.         }
  53.  
  54.         if (this.MoveNext())
  55.         {
  56.             string headerStr = (string)this.Current;
  57.  
  58.             string[] headers = headerStr.Split(delimiter);
  59.  
  60.             for (int i = 0; i < headers.Length; i++)
  61.             {
  62.                 if (headers[i].Equals(headerToReturn))
  63.                     headerPosition = i;
  64.             }
  65.         }
  66.     }
  67.  
  68.     public object Current
  69.     {
  70.         get {
  71.             if(headerPosition != -1)
  72.                 return line.Split(delimiter)[headerPosition];
  73.             else
  74.                 return line;
  75.         }
  76.     }
  77.  
  78.     public bool MoveNext()
  79.     {
  80.         line = sr.ReadLine();
  81.         return line != null;
  82.     }
  83.  
  84.     public void Reset()
  85.     {
  86.         if (sr != null)
  87.             sr.Close();
  88.  
  89.         sr = new StreamReader(fs);
  90.     }
  91. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top