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

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


当前回答

从文件中读取并写入文件的最简单方法:

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

其他回答

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

在读取时使用OpenFileDialog控件浏览到您想要读取的任何文件是很好的。找到下面的代码:

不要忘记添加以下using语句来读取文件:using System.IO;

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

要写入文件,可以使用File.WriteAllText方法。

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
    }