Menu

How to Read and Write to a CSV File in C#

Working with CSV files in C# can be accomplished through several approaches, with the most straightforward being the built-in File class methods combined with string manipulation.

For basic CSV operations, you can use File.ReadAllLines() to read the entire file into an array of strings, and File.WriteAllLines() to write data back to a CSV file.

However, for more robust CSV handling, it's recommended to use a dedicated CSV library like CsvHelper, which properly handles edge cases such as commas within quoted fields, escaped characters, and different cultural formats.

This library provides strongly-typed reading and writing capabilities, making it easier to map CSV data to C# objects.

For optimal performance and memory efficiency when dealing with large CSV files, you should consider using StreamReader and StreamWriter classes, which allow you to process the file line by line rather than loading it entirely into memory.

Remember to always properly dispose of these resources using using statements. When writing CSV data, be mindful of proper escaping and quoting rules – fields containing commas, quotes, or newlines should be enclosed in quotes and any embedded quotes should be doubled.

Example

// Basic CSV reading
string[] lines = File.ReadAllLines("data.csv");
foreach (string line in lines)
{
    string[] values = line.Split(',');
    // Process values
}

// Basic CSV writing
var data = new List<string[]>
{
    new[] { "Name", "Age", "City" },
    new[] { "John Doe", "30", "New York" }
};
File.WriteAllLines("output.csv", data.Select(line => string.Join(",", line)));

// Using StreamReader for large files
using (var reader = new StreamReader("data.csv"))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        // Process line
    }
}

// Using CsvHelper (requires NuGet package)
using (var reader = new StreamReader("data.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<MyClass>().ToList();
}
0
126

Related

In C#, you can format an integer with commas (thousands separator) using ToString with a format specifier.

int number = 1234567;
string formattedNumber = number.ToString("N0"); // "1,234,567"
Console.WriteLine(formattedNumber);

Explanation:

"N0": The "N" format specifier stands for Number, and "0" means no decimal places. The output depends on the culture settings, so in regions where , is the decimal separator, you might get 1.234.567.

Alternative:

You can also specify culture explicitly if you need a specific format:

using System.Globalization;

int number = 1234567;
string formattedNumber = number.ToString("N0", CultureInfo.InvariantCulture);
Console.WriteLine(formattedNumber); // "1,234,567"
2
113

Slow initial load times can drive users away from your React application. One powerful technique to improve performance is lazy loading - loading components only when they're needed.

Let's explore how to implement this in React.

The Problem with Eager Loading

By default, React bundles all your components together, forcing users to download everything upfront. This makes navigation much quicker and more streamlined once this initial download is complete.

However, depending on the size of your application, it could also create a long initial load time.

import HeavyComponent from './HeavyComponent';
import AnotherHeavyComponent from './AnotherHeavyComponent';

function App() {
  return (
    <div>
      {/* These components load even if user never sees them */}
      <HeavyComponent />
      <AnotherHeavyComponent />
    </div>
  );
}

React.lazy() to the Rescue

React.lazy() lets you defer loading components until they're actually needed:

import React, { lazy, Suspense } from 'react';

// Components are now loaded only when rendered
const HeavyComponent = lazy(() => import('./HeavyComponent'));
const AnotherHeavyComponent = lazy(() => import('./AnotherHeavyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <HeavyComponent />
        <AnotherHeavyComponent />
      </Suspense>
    </div>
  );
}

Route-Based Lazy Loading

Combine with React Router for even better performance:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

Implement these techniques in your React application today and watch your load times improve dramatically!

0
72

String interpolation, introduced in C# 6.0, provides a more readable and concise way to format strings compared to traditional concatenation (+) or string.Format(). Instead of manually inserting variables or placeholders, you can use the $ symbol before a string to directly embed expressions inside brackets.

string name = "Walt";
string job = 'Software Engineer';

string message = $"Hello, my name is {name} and I am a {job}";
Console.WriteLine(message);

This would produce the final output of:

Hello, my name is Walt and I am a Software Engineer

String interpolation can also be chained together into a multiline string (@) for even cleaner more concise results:

string name = "Walt";
string html = $@"
    <div>
        <h1>Welcome, {name}!</h1>
    </div>";
11
90