这个File
类来自 System.IO
命名空间,允许我们处理文件:
using System.IO; // include the System.IO namespace
File.SomeFileMethod(); // use the file class with methods
这个File
类有许多有用的方法来创建和获取有关文件的信息。例如:
Method | Description |
---|---|
AppendText() |
Appends text at the end of an existing file |
Copy() |
Copies a file |
Create() |
Creates or overwrites a file |
Delete() |
Deletes a file |
Exists() |
Tests whether the file exists |
ReadAllText() |
Reads the contents of a file |
Replace() |
Replaces the contents of a file with the contents of another file |
WriteAllText() |
Creates a new file and writes the contents to it. If the file already exists, it will be overwritten. |
有关 File 方法的完整列表,请访问Microsoft .Net 文件类参考。
在下面的示例中,我们使用WriteAllText()
方法创建一个名为 "filename.txt" 的文件并向其中写入一些内容。然后我们使用ReadAllText()
读取文件内容的方法:
using System.IO; // include the System.IO namespace
string writeText = "Hello World!"; // Create a text string
File.WriteAllText("filename.txt", writeText); // Create a file and write the content of writeText to it
string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
Console.WriteLine(readText); // Output the content
输出将是:
Hello World!
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!