Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert StreamReader to a string?

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);
}
like image 726
Jake H. Avatar asked Dec 22 '11 16:12

Jake H.


3 Answers

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();
}
like image 112
Adam Avatar answered Dec 21 '22 05:12

Adam


string content = String.Empty;

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

File.WriteAllText(outputPath, content, Encoding.UTF8);
like image 34
keyboardP Avatar answered Dec 21 '22 04:12

keyboardP


Use StreamReader.ReadToEnd() method.

like image 23
Sergei B. Avatar answered Dec 21 '22 06:12

Sergei B.