-1

How I can get byte[] from StreamWriter and download the file with what is written to streamwriter?

string document = @"C:\TestArea\Destination\SUP000011\ATM-1B4L2KQ0ZE0-0001\Sample.docx";
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
    string docText = null;

    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();                       
    }
    Regex regexText = new Regex("Hello world!");
    docText = regexText.Replace(docText, "Hi Everyone!");

    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    } 
}

Downloading code snippet -

  byte[] bytearraydata = Encoding.ASCII.GetBytes(doctext);
 if (bytearraydata != null)
                {
                    Response.ContentType = "Application/msword";
                    Response.AppendHeader("Content-disposition",
                            "attachment; filename=" + "Sample.docx");
                    Response.AppendHeader("content-length", bytearraydata.Length.ToString());
                    Response.BinaryWrite(bytearraydata);
                    Response.End();
                }
Bokambo
  • 4,204
  • 27
  • 79
  • 130

1 Answers1

0

Despite its name, StreamWriter actually writes characters, not bytes. If you want to write unencoded bytes use BinaryWriter.

To read unencoded bytes use BinaryReader.

Dour High Arch
  • 21,513
  • 29
  • 75
  • 90