最简单的文件读写方法

462

在C#中,有很多不同的方法可以读写文件(文本文件,而非二进制文件)。

我只需要一种简单且使用最少量代码的方法,因为在我的项目中我将经常处理文件。我只需要处理 string 类型,因为我只需要读写 string

14个回答

695
使用File.ReadAllTextFile.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);

这个页面列出了常见I/O任务的各种辅助方法。


2
非常简单,但为什么需要发布这个问题呢?OP可能像我和其他17个赞同者一样,沿着string.Write(filename)的方向寻找答案。为什么微软的解决方案比我的更简单/更好呢? - Roland
9
@Roland,在 .net 中,文件处理由框架提供,而不是语言本身(例如,没有 C# 关键字来声明和操作文件)。字符串是一个更常见的概念,以至于它是 C# 的一部分。因此,文件知道字符串是很自然的,但反过来则不然。 - vc 74
Xml在C#中也是一个常见的概念,例如我们可以使用XmlDocument.Save(filename)。但当然,不同之处在于通常一个Xml对象对应一个文件,而多个字符串组成一个文件。 - Roland
8
@Roland,如果你想支持 "foo".Write(fileName),你可以很容易地创建一个扩展来实现,例如 public static Write(this string value, string fileName) { File.WriteAllText(fileName, value);},并在你的项目中使用它。 - Alexei Levenkov
2
还有一个 File.WriteAllLines(filename, string[])。 - Mitch Wheat
显示剩余4条评论

209
除了已经在另一个答案中展示的File.ReadAllTextFile.ReadAllLinesFile.WriteAllText(以及File类的类似帮助程序),您还可以使用StreamWriter/StreamReader类。

编写文本文件:

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}

读取文本文件:

using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readText = readtext.ReadLine();
}

注意:

  • 您可以使用readtext.Dispose()代替using,但在出现异常时它不会关闭文件/读取器/写入器。
  • 请注意,相对路径是相对于当前工作目录的。您可能需要使用/构造绝对路径。
  • 缺少using/Close是“为什么数据没有写入文件”的非常普遍的原因。

3
请确保按照其他答案中显示的方式使用流 - https://dev59.com/0msz5IYBdhLWcg3w6MXn#7571213 - Alexei Levenkov
6
需要使用using System.IO;才能使用StreamWriterStreamReader - fat
1
还需注意,如果文件不存在,当StreamWriter尝试执行WriteLine时,它将创建该文件。在这种情况下,如果在调用WriteLine时write.txt文件不存在,则会创建该文件。 - Agrejus
5
值得注意的是,有一种向文件追加文本的方法:new StreamWriter("write.txt", true)。如果文件不存在,它将创建一个新文件,否则它会追加到现有文件中。 - ArieKanarie
值得注意的是,如果您将StreamReader和StreamWriter与FileStream一起使用(而不是文件名),则可以以只读模式和/或共享模式打开文件。 - Simon Zyx
显示剩余2条评论

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

1
为什么你不在结束时释放 fs - LuckyLikey
2
@LuckyLikey 因为 StreamReader 已经为您完成了这项工作。第二个 using 的嵌套是不必要的。 - Novaterata
你能解释一下吗?为什么应该对StreamReader进行处理,而不是fs?就我所知,它只能处理sr。我们需要在这里添加第三个using语句吗? - Philm
2
在 using 语句中,永远不要手动调用 Dispose 方法,因为当该语句返回时,Dispose 方法会自动被调用。无论这些语句是否嵌套,最终所有内容都会按照调用堆栈的顺序进行处理。 - Patrik Forsberg
1
当使用StreamReader(Stream)构造函数时,StreamReader对象在调用StreamReader.Dispose时会对提供的Stream对象调用Dispose()。还有另一个构造函数,它接受一个leaveOpen参数,如果您不想让Dispose也处理流,则可以使用该参数。 - user276648

15

从文件读取和写入文件的最简单方式:

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

6
为什么不使用File.WriteAllText来进行写入操作? - Peter Mortensen

11
using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

简单易用,同时在完成后自动清理/释放对象。


10

@AlexeiLevenkov指出了另一种"最简单的方法",即使用扩展方法。只需编写一点代码,便可提供绝对最容易的读取/写入方式,并且它还提供了根据您个人需求创建变化的灵活性。以下是完整的示例:

这定义了在string类型上的扩展方法。请注意,唯一真正重要的是带有额外关键字this的函数参数,这使它引用附加到方法的对象。类名不重要; 必须声明类和方法为静态

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

这是如何使用字符串扩展方法,请注意它自动引用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

我自己永远找不到这个,但它很有效,所以我想分享一下。祝你们玩得开心!


8
以下是编写和读取文件的最佳且最常用方法:
using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

在大学里我学习的旧方法是使用流读取器/流写入器,但文件I/O方法更为简洁,需要的代码行数更少。您可以在IDE中键入“File.”(确保包括System.IO导入语句)并查看所有可用的方法。以下是使用Windows Forms应用程序从文本文件(.txt)读取/写入字符串的示例方法。

将文本追加到现有文件:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

通过文件浏览器/打开文件对话框从用户那里获取文件名(您需要这个来选择现有文件)。
private string getFileNameFromUser()//returns file path\name
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

从现有文件中获取文本:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

5

如果你真的关注代码行数:

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

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

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

5

当阅读时,使用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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接