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:34

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);
查看更多
听够珍惜
3楼-- · 2018-12-31 19:37

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.

查看更多
皆成旧梦
4楼-- · 2018-12-31 19:38
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");
    }
}
查看更多
登录 后发表回答