0

I have the following code but it is just creating a 0kb empty file.

using (var stream1 = new MemoryStream())
{
    MemoryStream txtStream = new MemoryStream();
    Document document = new Document();
    fileInformation.Stream.CopyTo(stream1);
    document.LoadFromStream(stream1, FileFormat.Auto);
    document.SaveToStream(txtStream, FileFormat.Txt);

    StreamReader reader = new StreamReader(txtStream);
    string text = reader.ReadToEnd();
    System.IO.File.WriteAllText(fileName + ".txt", text);
 }

I know the data is successfully loaded into document because if do document.SaveToTxt("test.txt", Encoding.UTF8); instead of the SaveToStream line it exports the file properly.

What am I doing wrong?

Justin Braham
  • 123
  • 2
  • 11
  • 1
    You might need to reset the stream position to 0 before copying from one to the other. Take a look here for an example: https://stackoverflow.com/a/18766138/3617120 – awh112 Jun 06 '18 at 17:59
  • @awh112 I reset both streams (stream1, and txtStream) positions after calling SaveToStream and it worked!! Thank you very much! – Justin Braham Jun 06 '18 at 18:24
  • Happy to help! I'll go ahead and add it as an answer for future readers as well. – awh112 Jun 06 '18 at 18:27

1 Answers1

2

When copying a stream, you need to take care to reset the position to 0 if copying. As seen in the answer here, you can do something like this to your streams:

stream1.Position = 0;
txtStream.Position = 0;
awh112
  • 1,402
  • 4
  • 19
  • 33