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

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


当前回答

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

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

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

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

其他回答

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

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

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

File.WriteAllLines("./foo", myLines);
     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);
        }      
    }

从文件中读取

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

简单:

String inputText = "Hello World!";

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

var outputText = File.ReadAllText("yourfile.ext"); //reading
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
    }