【问题标题】:How do I convert StreamReader to a string?如何将 StreamReader 转换为字符串?
【发布时间】:2012-01-26 06:24:12
【问题描述】:

我更改了代码,以便可以只读方式打开文件。现在我无法使用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);
}

【问题讨论】:

  • StreamReader 不是string。使用您已注释掉的File.ReadAllText 方法将得到string
  • 看起来您只是将文件的内容复制到另一个目录。为什么不直接将文件复制到输出目录中?
  • 嘿,很高兴你能够解密我对你上一篇文章的评论......在你的 FileStream 上做一个using......你也需要在你做磁盘 IO 的任何时候尝试/捕捉...正如您已经看到的,有很多潜在的问题。除此之外,这些 StreamReader.ReadToEnd() 答案是您所需要的。
  • @docmanhattan 真正看起来像是一个学习练习。 :)

标签: c# streamreader


【解决方案1】:

使用 StreamReader 的 ReadToEnd() 方法:

string content = new StreamReader(fs, Encoding.Unicode).ReadToEnd();

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

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

【讨论】:

  • 我建议对流使用 using 语句。
  • 并使用 Path.Combine(...) 而不是字符串连接,我知道。我从我的答案中删除了噪音,只留下了改变的那一行
  • 因为我的回答已被接受,我已将其扩展为包含 @keyboardP 的回答中的 using 语句。
【解决方案2】:
string content = String.Empty;

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

File.WriteAllText(outputPath, content, Encoding.UTF8);

【讨论】:

  • +1 用于添加 using 语句来处理 StreamReader
【解决方案3】:

使用StreamReader.ReadToEnd() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 2018-04-30
    • 2014-05-26
    相关资源
    最近更新 更多