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