在c#中有很多不同的方法来读写文件(文本文件,而不是二进制文件)。

我只需要一些简单的东西,使用最少的代码,因为我将在我的项目中大量使用文件。我只需要一些字符串,因为我所需要的是读写字符串。


当前回答

简单:

String inputText = "Hello World!";

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

var outputText = File.ReadAllText("yourfile.ext"); //reading

其他回答

从文件中读取

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

写入文件

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

您正在寻找File、StreamWriter和StreamReader类。

使用文件。ReadAllText和File.WriteAllText。

MSDN示例节选:

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

或者,如果你真的很注重线条:

System.IO.File也包含一个静态方法WriteAllLines,所以你可以这样做:

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

File.WriteAllLines("./foo", myLines);