HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

Easiest way to read from and write to files

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromeasiestandwritefileswayread

Problem

There are a lot of different ways to read and write files (text files, not binary) in C#.

I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.

Solution

Use File.ReadAllText and File.WriteAllText.

MSDN example excerpt:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);


This page lists the various helper methods for common I/O tasks.

Code Snippets

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);

Context

Stack Overflow Q#7569904, score: 745

Revisions (0)

No revisions yet.