C# / .NET 튜토리얼

C#에서 텍스트 파일을 CSV로 변환

C#에서 텍스트 파일을 CSV로 변환하는 두 가지 방법: 간단한 데이터를 위한 StreamReader와 String.Split, 필드에 쉼표나 따옴표가 포함될 수 있을 때는 CsvHelper. Excel을 위한 UTF-8 출력 포함.

단계별Copy-paste codeFree converter included
광고
개요

Convert text to CSV in C#

On .NET you can convert text to CSV with built-in file APIs for simple cases, or with CsvHelper — the de-facto CSV library — when quoting and encoding need to be exactly right. Both are shown below with runnable code.

For a single file, the browser tool is faster; the C# code fits services, desktop apps and scheduled jobs.

Simple StreamReader + String.Split

For clean, tab-separated data this is all you need:

C# — StreamReader (simple)
using System.IO;
using System.Text;

string[] lines = File.ReadAllLines("input.txt", Encoding.UTF8);
// UTF8Encoding(true) writes a BOM so Excel reads it as UTF-8
using var writer = new StreamWriter("output.csv", false, new UTF8Encoding(true));
foreach (var line in lines)
{
    string[] fields = line.Split('\t');   // tab-delimited
    writer.WriteLine(string.Join(",", fields));
}

This version does not quote embedded commas — use CsvHelper if your fields can contain them.

CsvHelper for correct quoting

Install CsvHelper (NuGet: CsvHelper). Read the source with its delimiter and write properly quoted CSV:

C# — CsvHelper
using System.Globalization;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;

var inConfig = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = "\t" };
using var reader = new StreamReader("input.txt");
using var csvIn = new CsvReader(reader, inConfig);
using var writer = new StreamWriter("output.csv");
using var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture);

while (csvIn.Read())
{
    for (int i = 0; i < csvIn.Parser.Count; i++)
        csvOut.WriteField(csvIn.GetField(i));
    csvOut.NextRecord();
}

CsvHelper escapes fields containing commas, quotes or newlines, producing valid CSV automatically.

Keeping leading zeros and encoding

CSV stores text, so leading zeros survive in the file; it is Excel that strips them on open — see fix CSV Excel formatting issues. Writing with a UTF-8 BOM (as above) ensures Excel opens international characters correctly. For many files, wrap the conversion in a loop over Directory.GetFiles(".", "*.txt").

Good to know

Getting C# conversions right

For anything beyond clean tab- or space-separated input, prefer CsvHelper over String.Split: manual splitting cannot handle a value that contains the delimiter, an embedded quote or a line break, and those cases are exactly where data corruption hides. CsvHelper reads and writes to the standard, so the output re-imports everywhere.

Encoding deserves attention. Writing with new UTF8Encoding(true) emits a BOM that makes Excel open international characters correctly; omit it (new UTF8Encoding(false)) for files consumed by tools that dislike a BOM. Set the Delimiter on a CsvConfiguration to match your input, and use CultureInfo.InvariantCulture so number and date formatting do not vary by machine locale.

As with every language here, leading zeros survive in the CSV file itself — if they vanish, it is Excel reinterpreting the file on open, so apply the fix at the Excel import step. Verify by reading the output back with CsvHelper and checking the field count of the first few records.

For large files, avoid File.ReadAllLines, which loads everything into memory; read with a streaming StreamReader line by line, or let CsvHelper’s GetRecords yield records lazily. If you map rows to a strongly typed class, CsvHelper can read and write those objects directly, which is cleaner and less error-prone than indexing fields by position when the shape is fixed and known.

In short, reach for CsvHelper whenever data might contain commas, quotes or newlines, fall back to a simple split only for clean input, and always be explicit about encoding and culture. With those settled, the same conversion runs reliably inside a service, a desktop app or a scheduled task. The result is correct, properly quoted CSV that opens in Excel, Google Sheets and databases without any rework.

자주 묻는 질문

Convert Text File to CSV in C# — FAQ

How do I convert text to CSV in C#?

Read lines with StreamReader and join with commas, or use CsvHelper for automatic quoting.

Which library handles quoting?

CsvHelper reads and writes correctly quoted CSV, including embedded commas and newlines.

How do I write UTF-8 for Excel?

Use new UTF8Encoding(true) to include a BOM.

How do I convert many files?

Loop over Directory.GetFiles(".", "*.txt") and convert each.