如何转换的StreamReader为字符串? [英] How do I convert StreamReader to a string?

查看:163
本文介绍了如何转换的StreamReader为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我改变了我的代码,以便为只读,我可以打开一个文件。现在,我使用有问题 File.WriteAllText ,因为我的的FileStream 的StreamReader 不会转换为字符串



这是我的代码:

 静态无效的主要(字串[] args)
{
串inputPath = @C:\Documents和Settings\All Users\Application Data\
+ @Microsoft\Windows NT\MSFax\ActivityLog\OutboxLOG.txt
串outputPath = @C:\FAXLOG\OutboxLOG.txt

变种FS =新的FileStream(inputPath,FileMode.Open,FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete);
字符串内容=新的StreamReader(FS,Encoding.Unicode);

//字符串内容= File.ReadAllText(inputPath,Encoding.Unicode);
File.WriteAllText(outputPath,内容,Encoding.UTF8);
}


解决方案

使用ReadToEnd的()方法的StreamReader的:

 字符串内容=新的StreamReader(FS,Encoding.Unicode).ReadToEnd(); 

有,当然,重要的访问后关闭StreamReader的。因此,使用语句是有道理的,由 keyboardP 并按照建议。其他

 字符串内容;使用
(StreamReader的读者=新的StreamReader(FS,Encoding.Unicode))
{
含量= reader.ReadToEnd();
}


I altered my code so I could open a file as read only. Now I am having trouble using File.WriteAllText because my FileStream and StreamReader are not converted to a string.

This is my code:

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

解决方案

use the ReadToEnd() method of StreamReader:

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

It is, of course, important to close the StreamReader after access. Therefore, a using statement makes sense, as suggested by keyboardP and others.

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

这篇关于如何转换的StreamReader为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆