在 C# 中读取文件到字符串
本教程将讨论在 C# 中将文件的所有内容读取为字符串变量的方法。
在 C# 中使用 File.ReadAllText()
方法将文件读取为字符串
File
类提供了许多与 C# 中的文件进行交互的功能。C# 中的 File.ReadAllText()
方法(File.ReadAllText 方法(System.IO)| Microsoft Docs)读取文件的所有内容。File.ReadAllText()
方法将文件的路径作为参数,并以字符串变量返回指定文件的内容。请参见以下示例代码。
using System;
using System.IO;
namespace read_file_to_string
{
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText(@"C:\File\file.txt");
Console.WriteLine(text);
}
}
}
输出:
this is all the text in this file
在上面的代码中,我们使用 C# 中的 File.ReadAllText()
方法将路径 C:\File\
内文件 file.txt
的所有内容读取到字符串变量 text
中。
在 C# 中使用 StreamReader.ReadToEnd()
方法将文件读取为字符串
StreamReader
类从字节流中读取具有 C# 特定编码的内容。StreamReader.ReadToEnd()
方法用于读取 C# 中文件的所有内容。StreamReader.ReadToEnd()
方法以字符串变量返回指定文件的内容。请参见以下示例代码。
using System;
using System.IO;
namespace read_file_to_string
{
class Program
{
static void Main(string[] args)
{
StreamReader fileReader = new StreamReader(@"C:\File\file.txt");
string text = fileReader.ReadToEnd();
Console.WriteLine(text);
}
}
}
输出:
this is all the text in this file
在上面的代码中,我们使用 C# 中的 StreamReader.ReadToEnd()
方法将路径 C:\File\
内文件 file.txt
的所有内容读取到字符串变量 text
中。这种方法比以前的方法快得多。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。