How to properly maintain a PDF file

I am using .NET 3.5 ASP.NET. My website currently serves the PDF as follows:

context.Response.WriteFile(@"c:\blah\blah.pdf");

This works great. However, I would like to serve it using a method context.Response.Write(char [], int, int).

So, I tried to send the file through

byte [] byteContent = File.ReadAllBytes(ReportPath);
ASCIIEncoding encoding = new ASCIIEncoding();
char[] charContent = encoding.GetChars(byteContent);
context.Response.Write(charContent, 0, charContent.Length);

This did not work (for example, the plugin in the PDF browser complains that the file is damaged).

So, I tried the Unicode approach:

byte [] byteContent = File.ReadAllBytes(ReportPath);
UnicodeEncoding encoding = new UnicodeEncoding();
char[] charContent = encoding.GetChars(byteContent);
context.Response.Write(charContent, 0, charContent.Length);

which also did not work.

What am I missing?

+3
source share
3 answers

, "". , ASCII , ASCII 7 . , ASCIIEncoding 8- .

OutputStream Response.

, upfront, , . , , :

void LoadStreamToStream(Stream inputStream, Stream outputStream)
{
    const int bufferSize = 64 * 1024;
    var buffer = new byte[bufferSize];

    while (true)
    {
        var bytesRead = inputStream.Read(buffer, 0, bufferSize);
        if (bytesRead > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
        if ((bytesRead == 0) || (bytesRead < bufferSize))
            break;
    }
}

Response.OutputStream

LoadStreamToStream(fileStream, Response.OutputStream);

, :

void LoadFileToStream(string inputFile, Stream outputStream)
{
    using (var streamInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
    {
        LoadStreamToStream(streamInput, outputStream);
        streamInput.Close();
    }
}
+7

ContentType, - :

Response.ContentType = "application/octet-stream";
+2

Based on the answer of Peter Lillewold , I went and just made some extension methods for his functions above.

public static void WriteTo(this Stream inputStream, Stream outputStream)
{
    const int bufferSize = 64 * 1024;
    var buffer = new byte[bufferSize];

    while (true)
    {
        var bytesRead = inputStream.Read(buffer, 0, bufferSize);
        if (bytesRead > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
        if ((bytesRead == 0) || (bytesRead < bufferSize)) break;
    }
}

public static void WriteToFromFile(this Stream outputStream, string inputFile)
{
    using (var inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
    {
        inputStream.WriteTo(outputStream);
        inputStream.Close();
    }
}
0
source

Source: https://habr.com/ru/post/1730699/


All Articles