28

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);
}
Adam
  • 15,537
  • 2
  • 42
  • 63
Jake H.
  • 563
  • 2
  • 11
  • 23
  • `StreamReader` is not a `string`. Using the `File.ReadAllText` method you have commented out would get a `string`. – Samuel Slade Dec 22 '11 at 16:29
  • It looks like you are just copying the contents of a file to another directory. Why not make a copy of the file directly into the output directory? – docmanhattan Dec 22 '11 at 16:30
  • Hey, glad you was able to decypher my comment on your last post...do a `using` on your FileStream...also you need to try/catch anytime you're doing disk IO...as you have already seen, there are lots of potential problems. Other than that, these StreamReader.ReadToEnd() answers are what you need. – rfmodulator Dec 22 '11 at 16:33
  • @docmanhattan What it really looks like is a learning excercise. :) – rfmodulator Dec 22 '11 at 16:34

3 Answers3

66

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();
}
Community
  • 1
  • 1
Adam
  • 15,537
  • 2
  • 42
  • 63
  • 9
    I'd recommend using a `using` statement for streams. – albertjan Dec 22 '11 at 16:28
  • and using Path.Combine(...) instead of string concatenation, I know. I removed the noise from my answer leaving only the line that changed – Adam Dec 22 '11 at 16:31
  • 3
    Because my answer has been accepted, I've extended it to include a using statement as in @keyboardP's answer. – Adam Dec 22 '11 at 16:51
13
string content = String.Empty;

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

File.WriteAllText(outputPath, content, Encoding.UTF8);
keyboardP
  • 68,824
  • 13
  • 156
  • 205
4

Use StreamReader.ReadToEnd() method.

Sergei B.
  • 3,227
  • 19
  • 18