Last active
October 14, 2018 12:22
-
-
Save justincjahn/9844444 to your computer and use it in GitHub Desktop.
Quick & Dirty CSV Parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Parse a single line in CSV format. | |
| /// | |
| /// This method uses a character looping in lieu of String.Split for performance. You could | |
| /// squeeze more performance out of it by using .NET 4 MemoryMappedFiles for large reads and | |
| /// possibly pointer arithmatic instead of native C# looping. Using LinkedList may also help | |
| /// for really large lines. | |
| /// </summary> | |
| /// <param name="line">The line to parse.</param> | |
| /// <param name="delimiter">The delimiter that separates each value. Usually a comma.</param> | |
| /// <param name="qualifier">The encapsulation character of a value. Usually a double quote.</param> | |
| /// <returns>A list of strings.</returns> | |
| public List<string> ParseCSV(string line, char delimiter, char qualifier) | |
| { | |
| // The character buffer length | |
| int iBufferLength = 512; | |
| // The return list | |
| List<string> oReturn = new List<string>(); | |
| // Loop through each character | |
| char cCurrent; | |
| bool bEncapsulated = false; | |
| char[] acBuffer = new char[iBufferLength]; | |
| int iBuffer = 0; | |
| for (int i = 0; i < line.Length; i++) { | |
| cCurrent = line[i]; | |
| if (cCurrent.Equals(qualifier)) { | |
| bEncapsulated = !bEncapsulated; | |
| continue; | |
| } | |
| if (cCurrent.Equals(delimiter) && !bEncapsulated || line.Length == (i + 1)) { | |
| if (line.Length == (i + 1)) { | |
| acBuffer[iBuffer] = cCurrent; | |
| iBuffer++; | |
| } | |
| oReturn.Add(new string(acBuffer, 0, iBuffer)); | |
| Array.Clear(acBuffer, 0, iBufferLength); | |
| iBuffer = 0; | |
| continue; | |
| } | |
| acBuffer[iBuffer] = cCurrent; | |
| iBuffer++; | |
| } | |
| return oReturn; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment