如何将 StreamReader 转换为字符串?
Posted
技术标签:
【中文标题】如何将 StreamReader 转换为字符串?【英文标题】:How do I convert StreamReader to a string? 【发布时间】:2012-01-26 06:24:12 【问题描述】:我更改了代码,以便可以只读方式打开文件。现在我无法使用File.WriteAllText
,因为我的FileStream
和StreamReader
没有转换为字符串。
这是我的代码:
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 真正看起来像是一个学习练习。 :)
【参考方案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()
方法。
【讨论】:
以上是关于如何将 StreamReader 转换为字符串?的主要内容,如果未能解决你的问题,请参考以下文章
使用 StreamReader 读取 HttpContent 流直到字符限制
C# 无法通过换行符将字符串拆分为数组(来自 StreamReader)
C# StreamReader类和StreamWriter类