
Master CSV processing with our comprehensive guide. Learn basic to advanced techniques, enterprise solutions, performance optimization, security best practices, and future trends.
CSV processing C#, large CSV files, data validation, enterprise data processing, CSV security, performance optimization, .NET CSV, data import export, bulk data processing
Table of Contents
Introduction
Understanding CSV Format
Basic CSV Reading
Advanced CSV Processing
Enterprise Solutions
Real-World Case Studies
Performance Optimization
Security Considerations
Alternative Approaches
Future Trends
Introduction
CSV (Comma-Separated Values) remains one of the most ubiquitous data formats in the digital world. Despite its simplicity, CSV processing presents numerous challenges that can derail projects and cost businesses millions. This comprehensive guide explores CSV processing from basic implementations to enterprise-grade solutions.
Understanding CSV Format
The Complexity Behind Simple Format
public class CSVSpecification
{
// RFC 4180 Standard
public const string Delimiter = ",";
public const string TextQualifier = "\"";
public const string LineBreak = "\r\n";
// Common variations
public static readonly string[] AlternativeDelimiters = { ";", "|", "\t" };
public static readonly string[] AlternativeLineBreaks = { "\n", "\r" };
}Common CSV Challenges
Commas in data fields
Line breaks within quoted fields
Encoding issues (UTF-8, ASCII, etc.)
Inconsistent quoting
Large file handling
Malformed data recovery
Basic CSV Reading
Simple CSV Reader Implementation
public class BasicCSVReader
{
public static DataTable ReadCSV(string filePath)
{
DataTable dt = new DataTable();
using (StreamReader reader = new StreamReader(filePath))
{
// Read header
string headerLine = reader.ReadLine();
if (headerLine == null) return dt;
string[] headers = headerLine.Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header.Trim());
}
// Read data rows
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split(',');
if (fields.Length == headers.Length)
{
DataRow row = dt.NewRow();
for (int i = 0; i < fields.Length; i++)
{
row[i] = fields[i].Trim();
}
dt.Rows.Add(row);
}
}
}
return dt;
}
}Pros
Simple to understand
Minimal code
Quick implementation
Cons
No error handling
Doesn't handle quoted fields
No validation
Poor performance with large files
Advanced CSV Processing
Robust CSV Parser with Validation
public class AdvancedCSVProcessor
{
public class ProcessingResult
{
public DataTable Data { get; set; }
public ProcessingSummary Summary { get; set; }
public List<ProcessingError> Errors { get; set; }
public bool IsSuccess { get; set; }
public ProcessingResult()
{
Data = new DataTable();
Summary = new ProcessingSummary();
Errors = new List<ProcessingError>();
}
}
public class ProcessingSummary
{
public int TotalRows { get; set; }
public int ValidRows { get; set; }
public int InvalidRows { get; set; }
public TimeSpan ProcessingTime { get; set; }
public long MemoryUsed { get; set; }
}
public class ProcessingError
{
public int RowNumber { get; set; }
public string FieldName { get; set; }
public string ErrorMessage { get; set; }
public string RawData { get; set; }
public ErrorSeverity Severity { get; set; }
}
public enum ErrorSeverity
{
Warning,
Error,
Critical
}
public static ProcessingResult ProcessCSV(string filePath, CSVConfiguration config = null)
{
var result = new ProcessingResult();
var stopwatch = Stopwatch.StartNew();
long initialMemory = GC.GetTotalMemory(true);
try
{
config ??= CSVConfiguration.Default;
using (var reader = new StreamReader(filePath, config.Encoding))
{
ProcessHeaders(reader, result, config);
ProcessDataRows(reader, result, config);
}
result.IsSuccess = result.Errors.All(e => e.Severity != ErrorSeverity.Critical);
}
catch (Exception ex)
{
result.Errors.Add(new ProcessingError
{
ErrorMessage = $"Critical processing error: {ex.Message}",
Severity = ErrorSeverity.Critical
});
result.IsSuccess = false;
}
finally
{
stopwatch.Stop();
result.Summary.ProcessingTime = stopwatch.Elapsed;
result.Summary.MemoryUsed = GC.GetTotalMemory(false) - initialMemory;
}
return result;
}
private static void ProcessHeaders(StreamReader reader, ProcessingResult result, CSVConfiguration config)
{
string headerLine = reader.ReadLine();
if (headerLine == null)
{
result.Errors.Add(new ProcessingError
{
ErrorMessage = "File is empty or header missing",
Severity = ErrorSeverity.Critical
});
return;
}
string[] headers = ParseCSVLine(headerLine, config);
for (int i = 0; i < headers.Length; i++)
{
string columnName = SanitizeColumnName(headers[i], i);
result.Data.Columns.Add(columnName);
}
}
private static void ProcessDataRows(StreamReader reader, ProcessingResult result, CSVConfiguration config)
{
string line;
int rowNumber = 1;
while ((line = reader.ReadLine()) != null)
{
result.Summary.TotalRows++;
rowNumber++;
if (string.IsNullOrWhiteSpace(line))
{
result.Summary.InvalidRows++;
continue;
}
string[] fields = ParseCSVLine(line, config);
if (fields.Length != result.Data.Columns.Count)
{
result.Errors.Add(new ProcessingError
{
RowNumber = rowNumber,
ErrorMessage = $"Column count mismatch. Expected: {result.Data.Columns.Count}, Found: {fields.Length}",
Severity = ErrorSeverity.Error,
RawData = line
});
result.Summary.InvalidRows++;
continue;
}
DataRow row = result.Data.NewRow();
bool rowValid = true;
for (int i = 0; i < fields.Length; i++)
{
var validationResult = ValidateField(fields[i], result.Data.Columns[i].ColumnName, config);
if (!validationResult.IsValid)
{
result.Errors.Add(new ProcessingError
{
RowNumber = rowNumber,
FieldName = result.Data.Columns[i].ColumnName,
ErrorMessage = validationResult.ErrorMessage,
Severity = ErrorSeverity.Warning,
RawData = fields[i]
});
rowValid = false;
}
row[i] = SanitizeFieldValue(fields[i], config);
}
if (rowValid)
{
result.Data.Rows.Add(row);
result.Summary.ValidRows++;
}
else
{
result.Summary.InvalidRows++;
}
}
}
private static string[] ParseCSVLine(string line, CSVConfiguration config)
{
var fields = new List<string>();
var currentField = new StringBuilder();
bool inQuotes = false;
bool lastCharWasQuote = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == config.TextQualifier)
{
if (inQuotes)
{
if (i + 1 < line.Length && line[i + 1] == config.TextQualifier)
{
// Escaped quote
currentField.Append(config.TextQualifier);
i++;
}
else
{
inQuotes = false;
}
}
else
{
inQuotes = true;
}
lastCharWasQuote = true;
}
else if (c == config.Delimiter && !inQuotes)
{
fields.Add(currentField.ToString());
currentField.Clear();
lastCharWasQuote = false;
}
else
{
currentField.Append(c);
lastCharWasQuote = false;
}
}
fields.Add(currentField.ToString());
return fields.ToArray();
}
}
Join the conversation! Your thoughts help the community grow.