CSV

A lightweight extension that provides CVS functionality.

What is CSV?

CSV (Comma-Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. Each line of the file is a data record consisting of one or more fields, separated by commas. CSV files are widely used for data exchange between different applications and systems.

Name,Age,City
John,25,New York
Alice,30,"Los Angeles, CA"
Bob,28,Chicago

Features

  • Read CSV from file path

  • Parse CSV from string content or Unity TextAsset

  • Header row handling

  • Proper handling of quoted fields

  • Empty line skipping

  • Regex-based reliable parsing


Reading CSV

Reading from File

string filePath = "path/to/your/file.csv";
PathData pathData = PathData.Builder()
    .WithPath(filePath)
    .Build();

// Without header
foreach (string[] row in pathData.ReadAsCsv())
{
    // Process each row
    string firstColumn = row[0];
    string secondColumn = row[1];
}

// With header
foreach (string[] row in filePath.ReadAsCsv(hasHeader: true))
{
    // First row (header) is automatically skipped
}

Reading from Unity TextAsset

TextAsset csvTextAsset;

foreach (string[] row in csvTextAsset.ReadAsCsv(hasHeader: true))
{
    // Process each row
}

Reading Single Line

string line = "Field1,Field2,\"Field,3\"";
string[] fields = line.ReadCsvLine();
// fields = ["Field1", "Field2", "Field,3"]

Cache CSV Data

Read from file or TextAsset as CsvData.

PathData pathData = PathData.Builder()
    .WithPath("path", "to", "your")
    .WithPath("file.csv")
    .Build();
TextAsset csvTextAsset;

// Read from path
CsvData data = pathData.ReadAsCsvData(hasHeader: false);

// Read from TextAsset
CsvData data = csvTextAsset.ReadAsCsvData(hasHeader: true);

Use the CsvData

CsvData data;

// Header
bool data.HasHeader;
string[] data.Header;

// Loop Lines
foreach (var line in data.Lines)
{
    // your stuffs
}

// get line by index
// index not including header
string[] line = data[3];

// counts
int columnCount = data.ColumnCount;
int lineCount = data.LineCount;

Features Details

  • Quoted Field Support: Properly handles fields containing commas (e.g., "Los Angeles, CA")

  • Empty Line Handling: Automatically skips empty or whitespace-only lines

  • Header Row Option: Easily skip header row when needed

  • Multiple Input Sources: Support for file paths, strings, and Unity TextAssets

  • Memory Efficient: Uses IEnumerable for lazy evaluation

Best Practices

  • Always specify hasHeader explicitly for better code readability

  • Use appropriate method based on your data source (file/string/TextAsset)

  • Handle potential file not found exceptions when using ReadAsCsvFile

  • Consider line endings when working with different platforms

Last updated