// ------------------------------------------------------------------------------------------------------------- -------//<summary>//defines the Csvfilereader type.//</summary>//------------------------------------ --------------------------------------------------------------------------------namespace csvfilereader{using System; Using System.Collections.Generic; Using System.IO; Using System.Text; <summary>//Reads a CSV file. </summary> public class Csvfilereader {///<summary>//The stream reader to process The CSV file reading. </summary> private StreamReader StreamReader; <summary>//Initializes a new instance of the <see cref= "Csvfilereader"/> class. </summary>//<param name= "Csvfilepath" >//the CSV file path. </param>//<param name= "delimiter" >//The DeliMiter. </param> public Csvfilereader (String csvfilepath, char delimiter) {this. Csvfilepath = Csvfilepath; This. Delimiter = Delimiter; }///<summary>//finalizes An instance of the <see cref= "Csvfilereader"/> class. </summary> ~csvfilereader () {this. Close (); }///<summary>//Gets the CSV file path being read. </summary> public string Csvfilepath {get; private set;} <summary>//Gets the delimiter used within the CSV file. </summary> Public char Delimiter {get; private set;} <summary>//Read a line from the CSV file to a list of strings. </summary>//<returns>/The list of string. </returns> public list<string> ReadLine () {this. Open (); var resultelements = new list<string> (); try {var currentline = This.streamReader.ReadLine (); if (currentline! = null) {var currentlineelements = Currentline.split (this. Delimiter); Resultelements.addrange (currentlineelements); }} catch (Exception) {this. Close (); } return resultelements; }///<summary>//Opens the stream reader. </summary> private void Open () {if (This.streamreader = = null) { This.streamreader = new StreamReader (this. Csvfilepath, encoding.getencoding (1252)); }}///<summary>///Close the stream reader. </summary> private void Close () {if (This.streamreader = = null) { Return } this.streamReader.Close (); This.streamReader.Dispose (); } }}
// ------------------------------------------------------------------------------------------------------------- -------//<summary>//defines the program type.//</summary>//------------------------------------------ --------------------------------------------------------------------------namespace csvfilereader{using System; Using System.Collections.Generic; <summary>//The program. </summary> public static Class Program {///<summary>//The Main method. </summary> public static void Main () {var foo = new Csvfilereader (@ "C:\Users\Administr Ator\desktop\tmp.csv ", ', '); List<string> Line; while (line = foo. ReadLine ()). Count! = 0) {foreach (var item in line) {Console.Write (item + "|"); } Console.WriteLine (String. Empty); } } }}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
C #-CSV file Reader