455

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153

14 Answers14

688

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.

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • 2
    Very simple indeed, but why then was it needed to post the question? OP was probably, like myself and the 17 upvoters, looking in the "wrong" direction along the lines of `string.Write(filename)`. Why is Microsofts solution simpler / better than mine? – Roland Aug 21 '13 at 16:40
  • 8
    @Roland, In .net, file handling is provided by the framework, not the languages (there are no C# keywords to declare and manipulate files for instance). Strings are a more common concept, so common that it is part of C#. Therefore it is natural that files know about strings but not the opposite. – vc 74 Sep 14 '14 at 09:41
  • Xml is also a common concept with datatypes in C# and here we find e.g. XmlDocument.Save(filename). But of course the difference is that usually one Xml object corresponds with one file, while several strings form one file. – Roland Sep 15 '14 at 13:23
  • 8
    @Roland if you want to support `"foo".Write(fileName)` you can easily create extension to do so like `public static Write(this string value, string fileName) { File.WriteAllText(fileName, value);}` and use it in your projects. – Alexei Levenkov Feb 17 '15 at 23:23
  • @AlexeiLevenkov Thanks for your suggestion. I added the return type, and worked it out to a complete example, see below, because I it is not completely obvious how this works, and I will definitely have a need for this kind of programming. – Roland Feb 25 '15 at 09:43
  • FYI: As for all file operations I would suggest to encapsulate the code in a try/catch-block. – farosch Apr 04 '18 at 18:17
  • 2
    There is also File.WriteAllLines(filename, string[]) – Mitch Wheat May 21 '18 at 02:17
  • **So, so easy...** – Momoro Feb 17 '20 at 03:27
  • For those who want to add to the existing file without overwriting; `File.AppendAllText(path, content);` – MrAlbino May 10 '23 at 09:02
207

In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.

Writing a text file:

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}

Reading a text file:

using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readText = readtext.ReadLine();
}

Notes:

  • You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
  • Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
  • Missing using/Close is very common reason of "why data is not written to file".
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Bali C
  • 30,582
  • 35
  • 123
  • 152
  • 3
    Make sure to `using` your streams as shown in other answer - http://stackoverflow.com/a/7571213/477420 – Alexei Levenkov Feb 17 '15 at 23:19
  • 6
    Need `using System.IO;` to use *StreamWriter* and *StreamReader*. – fat Sep 09 '15 at 11:55
  • 1
    It should also be noted that if the file does not exist the StreamWriter will create the file when it attempts to WriteLine. In this case write.txt will be created if it doesn't exist when WriteLine is called. – Agrejus Sep 16 '16 at 13:33
  • 5
    Also worth noting is that there is an overload to append text to file: `new StreamWriter("write.txt", true)` It will create a file if not file doesn't exists, else it will append to existing file. – ArieKanarie Mar 22 '17 at 11:55
  • Also worth noting is that you if you use the streamreader and streamwriter in conjuction with a FileStream (pass it instead of the filename) you can open files in read-only mode and/or shared mode. – Simon Zyx Jul 11 '17 at 12:51
  • Although there exists a .ReadToEnd method on StreamReader – Simon Zyx Jul 11 '17 at 13:03
  • So I would use the `StreamWriter` approach if I want to write a line at a time, basically? Otherwise I don't see why you would use it over `File.WriteAllText` – Don Cheadle May 18 '18 at 14:03
24
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
   using (StreamWriter sw = new StreamWriter(Destination))
   {
            sw.Writeline("Your text");
    }
}
TidyDev
  • 3,470
  • 9
  • 29
  • 51
Swapnil
  • 251
  • 2
  • 2
  • 1
    Why don't you disponse `fs` at the end? – LuckyLikey May 27 '15 at 07:36
  • 2
    @LuckyLikey because StreamReader does that for you. The nesting of the 2nd using is not necessary however – Novaterata Apr 14 '17 at 19:45
  • Can you explain? Why should StreamReader dispose fs?? It can only dispose sr as far as I can see. Do we need a third using statement here? – Philm Apr 17 '17 at 17:56
  • 2
    You never Dispose an object in a using statement, when the statement is returned the Dispose method will be called automatically , and it does not matter if the statements are nested or not, in the end, everything is ordered in the call stack. – Patrik Forsberg Apr 07 '18 at 14:32
  • 1
    @Philm When using the `StreamReader(Stream)` constructor, `The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.`. There's another constructor that takes a `leaveOpen` argument, if you do not want `Dispose` to also dispose the stream. – user276648 Nov 03 '21 at 03:21
15

The easiest way to read from a file and write to a file:

//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");

//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
    writer.WriteLine(something);
}
Tsagana Nokhaeva
  • 630
  • 1
  • 6
  • 25
yazarloo
  • 187
  • 1
  • 4
11
using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

Simple, easy and also disposes/cleans up the object once you are done with it.

Ankit Dass
  • 521
  • 5
  • 7
10

@AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:

This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.

using System.IO;//File, Directory, Path

namespace Lib
{
    /// <summary>
    /// Handy string methods
    /// </summary>
    public static class Strings
    {
        /// <summary>
        /// Extension method to write the string Str to a file
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="Filename"></param>
        public static void WriteToFile(this string Str, string Filename)
        {
            File.WriteAllText(Filename, Str);
            return;
        }

        // of course you could add other useful string methods...
    }//end class
}//end ns

This is how to use the string extension method, note that it refers automagically to the class Strings:

using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            "Hello World!".WriteToFile(@"c:\temp\helloworld.txt");
            return;
        }

    }//end class
}//end ns

I would never have found this myself, but it works great, so I wanted to share this. Have fun!

Roland
  • 4,619
  • 7
  • 49
  • 81
8

These are the best and most commonly used methods for writing to and reading from files:

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

Append text to an existing file:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

private string getFileNameFromUser()//returns file path\name
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

Get text from an existing file:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
SendETHToThisAddress
  • 2,756
  • 7
  • 29
  • 54
5

It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:

Don't forget to add the following using statement to read files: using System.IO;

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
         textBox1.Text = File.ReadAllText(openFileDialog1.FileName);  
    }
}

To write files you can use the method File.WriteAllText.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tassisto
  • 9,877
  • 28
  • 100
  • 157
5

Or, if you are really about lines:

System.IO.File also contains a static method WriteAllLines, so you could do:

IList<string> myLines = new List<string>()
{
    "line1",
    "line2",
    "line3",
};

File.WriteAllLines("./foo", myLines);
anhoppe
  • 4,287
  • 3
  • 46
  • 58
2
     class Program
    { 
         public static void Main()
        { 
            //To write in a txt file
             File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");

           //To Read from a txt file & print on console
             string  copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
             Console.Out.WriteLine("{0}",copyTxt);
        }      
    }
Md.Rakibuz Sultan
  • 759
  • 1
  • 8
  • 13
1
private void Form1_Load(object sender, EventArgs e)
    {
        //Write a file
        string text = "The text inside the file.";
        System.IO.File.WriteAllText("file_name.txt", text);

        //Read a file
        string read = System.IO.File.ReadAllText("file_name.txt");
        MessageBox.Show(read); //Display text in the file
    }
Alireza.m
  • 11
  • 1
0
  1. Reading from file
string filePath = @"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
  1. Writing to file
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);
markonius
  • 625
  • 6
  • 25
Daniel
  • 1
0

Simply:

String inputText = "Hello World!";

File.WriteAllText("yourfile.ext",inputText); //writing

var outputText = File.ReadAllText("yourfile.ext"); //reading
Majid
  • 13,853
  • 15
  • 77
  • 113
-1

You're looking for the File, StreamWriter, and StreamReader classes.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 10
    Very unhelpful answer. The means the OP must now go google these terms in hopes of finding an answer. The best answer is an example. – tno2007 Aug 08 '17 at 15:58
  • why is this at the top? stack overflow wasting my time having me scroll more to get the better answer.. – user55665484375 Jan 10 '23 at 03:33
  • @user55665484375 You can use the "Sorted by:" dropdown to change the order that the answers are listed. – eksortso Feb 15 '23 at 08:36