Easiest way to read from and write to files

2018-12-31 19:00发布

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.

9条回答
浮光初槿花落
2楼-- · 2018-12-31 19:25

Use File.ReadAllText and File.WriteAllText.

It could not be simpler...

MSDN examples:

// 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);
查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 19:25

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 readMeText = readtext.ReadLine();
}

Notes:

  • You can use readtext.Close() 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".
查看更多
步步皆殇っ
4楼-- · 2018-12-31 19:30

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

查看更多
长期被迫恋爱
5楼-- · 2018-12-31 19:32
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.

查看更多
何处买醉
6楼-- · 2018-12-31 19:32

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);
}
查看更多
何处买醉
7楼-- · 2018-12-31 19:32

@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 namespace and class declarations are optional.

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!

查看更多
登录 后发表回答