Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to read from and write to files

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.

like image 733
ApprenticeHacker Avatar asked Sep 27 '11 13:09

ApprenticeHacker


People also ask

Can you read and write to a file at the same time?

It is possible to read and write the same file at different times, and it is possible to read one file and write another at the same time, but it isn't possible to read and write the same file at the same time.

What are the three steps required to read from or write to a file?

When a file is used by a program, three steps must be taken. Open the file — Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the disk and allows the program to write data to it. Opening an input file allows the program to read data from the file.


1 Answers

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); 
like image 161
vc 74 Avatar answered Nov 16 '22 00:11

vc 74