用 C# 读写文件
-
在 C# 中使用
File.WriteAllText()方法将数据写入文件 -
使用 C# 中的
File.ReadAllText()方法从文件读取数据 -
在 C# 中使用
StreamWriter类将数据写入文件 -
在 C# 中使用
StreamReader类从文件中读取数据
本教程将讨论使用 C# 从文件读取数据或将数据写入文件的方法。
在 C# 中使用 File.WriteAllText() 方法将数据写入文件
File 类提供使用 C# 处理文件的功能。File.WriteAllText(path) 方法可用于在路径 path 中向文件中写入一些字符串。以下代码示例向我们展示了如何使用 C# 中的 File.WriteAllText() 函数将数据写入文件。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string Text = "Hello, Hi, ByeBye";
File.WriteAllText(path, Text);
}
}
}
file.txt 内容:
Hello, Hi, ByeBye
在上面的代码中,我们在路径 C:\File 内创建了一个文本文件 file.txt,并使用 File.WriteAllText(path, Text) 函数在 C# 中的功能。
使用 C# 中的 File.ReadAllText() 方法从文件读取数据
File.ReadAllText() 方法可用于以字符串变量的形式从文件中读取数据。File.ReadAllText() 方法将文件的路径作为参数,并以字符串数据类型返回文件的内容。以下代码示例向我们展示了如何使用 C# 中的 File.ReadAllText() 方法从文件读取数据。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
}
输出:
Hello, Hi, ByeBye
在上面的代码中,我们使用 File.ReadAllText(path) 方法读取了先前写入 C:\File 目录内的 file.txt 文件的所有数据,并将其显示给用户。
在 C# 中使用 StreamWriter 类将数据写入文件
StreamWriter 类用于以 C# 的特定编码将数据写入流。StreamWrite.WriteLine() 方法可用于将字符串变量写入文件。以下代码示例向我们展示了如何使用 C# 中的 StreamWriter.WriteLine() 方法将数据写入文件。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string Text = "Hello and Welcome";
using (StreamWriter writetext = new StreamWriter(path)) {
writetext.WriteLine(Text);
}
}
}
}
file.txt 内容:
Hello and Welcome
在上面的代码中,我们创建了一个 StreamWriter 类的对象,并将字符串变量 Text 与 writetext.WriteLine(Text) 一起写入了 C:\File 目录内的 file.txt 文件中。C# 中的函数。
在 C# 中使用 StreamReader 类从文件中读取数据
StreamReader 类用于以 C# 的特定编码从流中读取数据。StreamReader.ReadLine() 方法可用于从文件中读取字符串数据。以下代码示例向我们展示了如何使用 C# 中的 StreamReader.ReadLine() 方法从文件中读取数据。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
using (StreamReader readtext = new StreamReader(path)) {
string readText = readtext.ReadLine();
Console.WriteLine(readText);
}
}
}
}
输出:
Hello and Welcome
在上面的代码中,我们创建了 StreamReader 类的对象,并使用 readtext.ReadLine() 函数读取了先前写入 C:\File 目录内的 file.txt 文件的所有数据,并向用户显示了它。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn