c# - 如何将 StreamReader 转换为字符串?

标签 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);
}

最佳答案

使用 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();
}

关于c# - 如何将 StreamReader 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606793/

相关文章:

VB.Net:按行搜索Word文档

c# - 更快地读取文件并快速获取像素颜色?

windows - Vb.net 读取文件后不关闭文件

c# - 在C#中读取大文件

c# - 不应加载引用程序集来执行。它们只能在仅反射加载器上下文中加载

c# - XDocument、XPath 和命名空间的奇怪之处

c# - 如何排除与 ASP.Net 中 HttpHandler 的指定路径匹配的内容?

c# - 在 C# 中,如何复制具有任意编码的文件,逐行读取,而不添加或删除换行符

c# - 如何在 Outlook 中显示系统发送的电子邮件中的背景图像?

c# - 如何在 MVC View 中更改显示格式