ChatGPT解决这个技术问题 Extra ChatGPT

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.


v
vc 74

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);

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, 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.
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 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.
There is also File.WriteAllLines(filename, string[])
Y
Yousha Aleayoub

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".


Make sure to using your streams as shown in other answer - stackoverflow.com/a/7571213/477420
Need using System.IO; to use StreamWriter and StreamReader.
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.
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.
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.
T
TidyDev
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");
    }
}

Why don't you disponse fs at the end?
@LuckyLikey because StreamReader does that for you. The nesting of the 2nd using is not necessary however
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?
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.
@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.
A
Ankit Dass
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.


T
Tsagana Nokhaeva

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);
}

Why not File.WriteAllText for writing part?
R
Roland

@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!


S
SendETHToThisAddress

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
}

a
anhoppe

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);

P
Peter Mortensen

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.


M
Md.Rakibuz Sultan
     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);
        }      
    }

A
Alireza.m
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
    }

m
markonius

Reading from file

string filePath = @"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();

Writing to file

List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);

` = new List();` is unnecessary as you overwrite the variable immediately in the next line.
S
SLaks

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


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.