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

App*_*ker 318 .net c# string file-io file

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

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

vc *_* 74 511

使用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);
Run Code Online (Sandbox Code Playgroud)

  • @Roland如果你想支持`"foo".Write(fileName)`你可以很容易地创建扩展来像`public static Write(this string value,string fileName){File.WriteAllText(fileName,value);}`并在您的项目中使用它. (7认同)
  • @Roland,在.net中,文件处理由框架提供,而不是语言(例如,没有C#关键字来声明和操作文件).字符串是一个更常见的概念,很常见,它是C#的一部分.因此,文件知道字符串而不是相反的文件是很自然的. (6认同)
  • 确实很简单,但是为什么要发布这个问题呢?OP可能像我自己和17个支持者一样,沿着“ string.Write(filename)”的方向朝着“错误”的方向看。为什么Microsoft的解决方案比我的解决方案更简单/更好? (2认同)
  • 还有 File.WriteAllLines(filename, string[]) (2认同)

Bal*_*i C 155

此外File.ReadAllText,File.ReadAllLinesFile.WriteAllText(距离和类似佣工File所示类),另一种答案,你可以使用StreamWriter/ StreamReader班.

编写文本文件:

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}
Run Code Online (Sandbox Code Playgroud)

阅读文本文件:

using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readMeText = readtext.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您可以使用readtext.Close()而不是using,但在异常的情况下它不会关闭文件/读取器/写入器
  • 请注意,相对路径是相对于当前工作目录的.您可能想要使用/构造绝对路径.
  • 缺少using/ Close是"为什么数据不写入文件"的常见原因.

  • 需要`使用System.IO;`使用*StreamWriter*和*StreamReader*. (4认同)
  • 确保"使用"您的流,如其他答案所示 - http://stackoverflow.com/a/7571213/477420 (3认同)
  • 另外值得注意的是,将文本附加到文件有一个重载:`new StreamWriter("write.txt",true)`如果不存在文件,它将创建一个文件,否则它将附加到现有文件. (3认同)

小智 18

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @LuckyLikey 因为 StreamReader 会为你做到这一点。然而,第二次使用的嵌套不是必需的 (2认同)
  • 你永远不会在using语句中Dispose一个对象,当该语句返回时,Dispose方法将被自动调用,并且无论语句是否嵌套,最终,所有内容都在调用堆栈中排序。 (2认同)

Ank*_*ass 11

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

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}
Run Code Online (Sandbox Code Playgroud)

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


小智 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不用`File.WriteAllText`来写部分? (5认同)

Rol*_*and 9

@AlexeiLevenkov用另一种"最简单的方法"指出了扩展方法.它只需要一点点编码,然后提供绝对最简单的读/写方式,而且它可以根据您的个人需求灵活地创建变化.这是一个完整的例子:

这定义了string类型的扩展方法.请注意,唯一真正重要的是带有extra关键字的函数参数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
Run Code Online (Sandbox Code Playgroud)

这是如何使用static,注意它自动引用到string extension method:

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
Run Code Online (Sandbox Code Playgroud)

我自己永远都找不到,但它很有效,所以我想分享一下.玩得开心!


Tas*_*sto 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);  
    }
}
Run Code Online (Sandbox Code Playgroud)

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


anh*_*ppe 5

或者,如果您确实是关于行的:

System.IO.File还包含一个静态方法WriteAllLines,因此您可以执行以下操作:

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

File.WriteAllLines("./foo", myLines);
Run Code Online (Sandbox Code Playgroud)


tec*_*n23 5

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

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);
Run Code Online (Sandbox Code Playgroud)

我在大学里曾教过的一种旧方法是使用流读取器/流写入器,但是File I / O方法比较笨拙,需要更少的代码行。您可以输入“文件”。在您的IDE中(确保您包括System.IO import语句)并查看所有可用方法。下面是使用Windows Forms App从文本文件(.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
Run Code Online (Sandbox Code Playgroud)

通过文件资源管理器/打开文件对话框从用户获取文件名(您将需要使用它来选择现有文件)。

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
Run Code Online (Sandbox Code Playgroud)

从现有文件获取文本:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
Run Code Online (Sandbox Code Playgroud)