【问题标题】:Easiest way to read from and write to files读取和写入文件的最简单方法
【发布时间】:2011-09-27 13:25:48
【问题描述】:

在 C# 中读取和写入文件(文本文件,不是二进制文件)有很多不同的方法。

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

【问题讨论】:

    标签: c# .net string file file-io


    【解决方案1】:

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

    【讨论】:

    • 确实很简单,但是为什么需要发布这个问题呢? OP 可能像我和 17 位支持者一样,沿着string.Write(filename) 的方向寻找“错误”的方向。为什么微软的解决方案比我的更简单/更好?
    • @Roland,在 .net 中,文件处理由框架提供,而不是由语言提供(例如,没有 C# 关键字来声明和操作文件)。字符串是一个更常见的概念,如此普遍以至于它是 C# 的一部分。因此,文件知道字符串是很自然的,但不知道相反。
    • Xml 也是 C# 中数据类型的常见概念,在这里我们可以找到例如XmlDocument.Save(文件名)。但当然不同的是,通常一个xml对象对应一个文件,而多个字符串组成一个文件。
    • @Roland 如果你想支持"foo".Write(fileName),你可以轻松地创建扩展来做到这一点,比如public static Write(this string value, string fileName) { File.WriteAllText(fileName, value);},并在你的项目中使用它。
    • 还有File.WriteAllLines(filename, string[])
    【解决方案2】:

    除了another answer 中显示的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 是“为什么没有将数据写入文件”的非常常见的原因。

    【讨论】:

    • 确保using您的流,如其他答案所示 - stackoverflow.com/a/7571213/477420
    • 需要 using System.IO; 才能使用 StreamWriterStreamReader
    • 还应注意,如果文件不存在,StreamWriter 将在尝试 WriteLine 时创建文件。在这种情况下,如果调用 WriteLine 时 write.txt 不存在,则会创建它。
    • 另外值得注意的是,将文本附加到文件有一个重载:new StreamWriter("write.txt", true) 如果不是文件不存在,它将创建一个文件,否则它将附加到现有文件。
    • 另外值得注意的是,如果您将流读取器和流写入器与 FileStream 结合使用(传递它而不是文件名),您可以以只读模式和/或共享模式打开文件。
    【解决方案3】:
    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");
        }
    }
    

    【讨论】:

    • 最后你为什么不处理fs
    • @LuckyLikey 因为 StreamReader 会为您做到这一点。然而,第二次使用的嵌套不是必需的
    • 你能解释一下吗?为什么 StreamReader 应该处理 fs?据我所知,它只能处理 sr 。这里需要第三个 using 语句吗?
    • 你永远不会在 using 语句中 Dispose 一个对象,当该语句返回时 Dispose 方法会被自动调用,不管语句是否嵌套,最后一切都是在调用堆栈中排序。
    • @Philm 当使用StreamReader(Stream) 构造函数时,The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.。如果您不希望 Dispose 也处理流,还有另一个构造函数接受 leaveOpen 参数。
    【解决方案4】:
    using (var file = File.Create("pricequote.txt"))
    {
        ...........                        
    }
    
    using (var file = File.OpenRead("pricequote.txt"))
    {
        ..........
    }
    

    简单、容易,并且在您完成对象后也可以处理/清理它。

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

      • 为什么不File.WriteAllText 写部分?
      【解决方案6】:

      @AlexeiLevenkov 向我指出了另一种“最简单的方法”,即extension method。它只需要一点编码,然后提供最简单的读/写方式,此外它还提供了根据您的个人需求创建变化的灵活性。这是一个完整的例子:

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

      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
      

      这是string extension method的使用方法,注意它自动引用class 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
      

      我自己永远不会找到这个,但它很好用,所以我想分享这个。玩得开心!

      【讨论】:

        【解决方案7】:

        这些是写入和读取文件的最佳和最常用的方法:

        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 中(确保包含 System.IO 导入语句)并查看所有可用的方法。下面是使用 Windows 窗体应用程序从文本文件 (.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
        }
        

        【讨论】:

          【解决方案8】:

          或者,如果你真的很喜欢线条:

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

          IList<string> myLines = new List<string>()
          {
              "line1",
              "line2",
              "line3",
          };
          
          File.WriteAllLines("./foo", myLines);
          

          【讨论】:

            【解决方案9】:

            阅读时最好使用 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

            【讨论】:

              【解决方案10】:
                   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);
                      }      
                  }
              

              【讨论】:

                【解决方案11】:
                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
                    }
                

                【讨论】:

                  【解决方案12】:

                  您正在寻找 FileStreamWriterStreamReader 类。

                  【讨论】:

                  • 非常无益的答案。这意味着 OP 现在必须去谷歌搜索这些术语,希望能找到答案。最好的答案是一个例子。
                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-01-04
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-15
                  • 1970-01-01
                  • 2017-09-15
                  相关资源
                  最近更新 更多