首页 文章

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

提问于
浏览
262

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

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

9 回答

  • 4

    您正在寻找 FileStreamWriterStreamReader 类 .

  • 10

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

    //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);
    }
    
  • 8
    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");
        }
    }
    
  • 0

    @AlexeiLevenkov指着我另一个"easiest way",即extension method . 它只需要一点点编码,然后提供绝对最简单的读/写方式,而且它可以根据您的个人需求灵活地创建变化 . 这是一个完整的例子:

    这定义了 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
    

    这是如何使用 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
    

    我自己也永远不会发现这个,但是效果很好,所以我想分享一下 . 玩得开心!

  • 14

    在阅读时使用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 .

  • 421

    除了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 readMeText = readtext.ReadLine();
    }
    

    笔记:

    • 您可以使用readtext.Close()而不是using,但如果出现异常则不会关闭文件/阅读器/编写器

    • 请注意,相对路径是相对于当前工作目录的 . 您可能想要使用/构造绝对路径 .

    • 缺少 using / Close 是"why data is not written to file"非常常见的原因 .

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

    一旦完成,它就简单,容易并且还可以处理/清理对象 .

  • 3

    或者,如果你真的是关于线:

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

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

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

相关问题