如何将StreamReader转换为字符串?
我修改了我的代码,因此我可以将文件打开为只读。 现在我无法使用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很重要。 因此,正如keyboardP和其他人所建议的那样, using
语句是有意义的。
string content; using(StreamReader reader = new StreamReader(fs, Encoding.Unicode)) { content = reader.ReadToEnd(); }
string content = String.Empty; using(var sr = new StreamReader(fs, Encoding.Unicode)) { content = sr.ReadToEnd(); } File.WriteAllText(outputPath, content, Encoding.UTF8);
使用StreamReader.ReadToEnd()
方法。