NewsCSVHandler

Overview

CSV import/export utility for NewsData. Each CSV line represents a single news item. Reading is tolerant to an optional header and supports quoted values with escaped quotes; writing can optionally include a header and always handles quoting/escaping correctly.

Public API

NewsData ReadNewsFromCSV(string path);
void WriteNewsToCSV(NewsData data, string path, bool includeHeader = true);

ReadNewsFromCSV(path)

  • Validates path and existence; logs errors/warnings and returns an empty NewsData if invalid.
  • Detects encoding (UTF‑8 with or without BOM) and reads all lines.
  • Skips the first line if it looks like a header: News or Text (case‑insensitive, quotes allowed).
  • For each remaining line:
    • Trims whitespace, skips empty lines.
    • Unquotes CSV‑style strings: leading/trailing quotes removed; """.
    • Appends the cleaned string to data.items.

WriteNewsToCSV(data, path, includeHeader)

  • Validates inputs; logs errors and returns on failure.
  • Ensures the target directory exists.
  • Opens a StreamWriter using UTF‑8 with BOM.
  • If includeHeader == true, writes a single header line: News.
  • Writes each item on its own line, quoting/escaping as needed.

Escaping Rules

  • A value is quoted if it contains any of: , ; " linebreak (\n/\r).
  • When quoted, internal " become "" (standard CSV escaping).

Encoding

  • Read: naive BOM detection → UTF‑8 (BOM) if present, otherwise UTF‑8 (no BOM).
  • Write: UTF‑8 with BOM for maximum compatibility with common editors.

Error Handling

  • Uses Debug.LogError/Warning with clear prefixes so issues are easy to spot in logs.

Minimal CSV Schema

News
"First news item"
"Another, longer item with a comma"
"Supports ""escaped quotes"" correctly"

Example

var data = NewsCSVHandler.ReadNewsFromCSV(path);
data.items.Add("Hotfix 1.0.3 deployed");
NewsCSVHandler.WriteNewsToCSV(data, path, includeHeader:true);