Home >Backend Development >C++ >How Can I Efficiently Read and Handle Corrupted CSV Files in C#?
C# applications frequently process CSV files. However, corrupted data can pose significant challenges. This guide demonstrates optimized CSV reading in C#, focusing on handling corrupted lines effectively.
Avoid manual CSV value splitting. The Microsoft.VisualBasic
namespace provides the TextFieldParser
class, simplifying parsing by defining field types and delimiters.
<code class="language-csharp">using Microsoft.VisualBasic; using Microsoft.VisualBasic.FileIO; using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv")) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); }</code>
Before processing each row, implement checks to identify corrupted lines. For instance, a row with fewer than 5 values might indicate corruption:
<code class="language-csharp">while (!parser.EndOfData) { string[] fields = parser.ReadFields(); if (fields.Length < 5) { // Handle corrupted line - e.g., log it or add it to a separate grid for review. } else { // Process valid row } }</code>
For enhanced error handling and more sophisticated data validation, consider these resources:
The above is the detailed content of How Can I Efficiently Read and Handle Corrupted CSV Files in C#?. For more information, please follow other related articles on the PHP Chinese website!