将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
将文本文件读入字符串变量的最快方法是什么?
我理解它可以通过几种方式完成,比如读取单个字节,然后将它们转换为字符串。我在寻找一种编码最少的方法。
当前回答
string content = System.IO.File.ReadAllText( @"C:\file.txt" );
其他回答
你可以使用:
public static void ReadFileToEnd()
{
try
{
//provide to reader your complete text file
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
如果你想从应用程序的Bin文件夹中选择文件,那么你可以尝试以下操作,不要忘记做异常处理。
string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));
你可以这样用
public static string ReadFileAndFetchStringInSingleLine(string file)
{
StringBuilder sb;
try
{
sb = new StringBuilder();
using (FileStream fs = File.Open(file, FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
string str;
while ((str = sr.ReadLine()) != null)
{
sb.Append(str);
}
}
}
}
return sb.ToString();
}
catch (Exception ex)
{
return "";
}
}
希望这对你有所帮助。
File怎么样?ReadAllText:
string contents = File.ReadAllText(@"C:\temp\test.txt");