如何将StreamReader转换为字符串?

Jak*_* H. 18 c# streamreader

我修改了我的代码,因此我可以将文件打开为只读.现在我无法使用,File.WriteAllText因为我的FileStreamStreamReader没有转换为字符串.

这是我的代码:

static void Main(string[] args)
{
    string inputPath = @"C:\Documents and Settings\All Users\Application Data\"
                     + @"Microsoft\Windows NT\MSFax\ActivityLog\OutboxLOG.txt";
    string outputPath = @"C:\FAXLOG\OutboxLOG.txt";

    var fs = new FileStream(inputPath, FileMode.Open, FileAccess.Read,
                                      FileShare.ReadWrite | FileShare.Delete);
    string content = new StreamReader(fs, Encoding.Unicode);

    // string content = File.ReadAllText(inputPath, Encoding.Unicode);
    File.WriteAllText(outputPath, content, Encoding.UTF8);
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 45

使用StreamReader的ReadToEnd()方法:

string content = new StreamReader(fs, Encoding.Unicode).ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

当然,在访问后关闭StreamReader很重要.因此,using正如keyboardP和其他人所建议的那样,语句是有意义的.

string content;
using(StreamReader reader = new StreamReader(fs, Encoding.Unicode))
{
    content = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议对流使用`using`语句. (9认同)
  • 因为我的答案已被接受,所以我将其扩展为包含@ keyboardP答案中的using语句. (3认同)

key*_*rdP 13

string content = String.Empty;

using(var sr = new StreamReader(fs, Encoding.Unicode))
{
     content = sr.ReadToEnd();
}

File.WriteAllText(outputPath, content, Encoding.UTF8);
Run Code Online (Sandbox Code Playgroud)

  • +1用于添加using语句以处置StreamReader (3认同)