Search code examples
c#httpmemoryiostream

How do I read the correct Stream/byte[] from HttpPostedFile InputStream property?


I get a HttpPostedFile that is being uploaded (supposedly a pdf), and I have to use it's stream to initialize it in PdfSharp.

The problem is that, altough HttpPostedFile SaveAs() method saves a valid pdf, saving it's InputStream doesn't create a valid pdf, so when I use the InputStream on PdfSharp to read the pdf it throws an exception with "Invalid Pdf", and saving the InputStream byte[] which I tried to get like this:

    public byte[] GetBytesFromStream(System.IO.Stream uploadedFile)
    {
        int length = Convert.ToInt32(uploadedFile.Length); //Length: 103050706
        string str = "";

        byte[] input = new byte[length];

        // Initialize the stream.
        System.IO.Stream MyStream = uploadedFile;

        // Read the file into the byte array.
        MyStream.Read(input, 0, length);
        
        return input;
    }

Calling the method like this:

byte[] fileBytes = GetBytesFromStream(uploadedFile.InputStream);

But creating a file from those bytes creates an invalid pdf too...

I created the file from bytes like this...

System.IO.File.WriteAllBytes("Foo.pdf", fileBytes);

I have 2 questions about this then:

1st - Why is the stream I receive from the InputStream invalid, and the SaveAs Works.

2nd - How could I get the correct stream from the inputStream or the HttpPostedFile, without saving the file to disk and then reading it.


Solution

  • Noticed that this question wasn't answered (since Evk's comment was the solution) and I couldn't accept any answer.

    So I'm making this one just to not leave this question unanswered.

    tl;dr; The solution as per Evk's comment was the position of the stream, it was being read beforehand and setting the position to 0 before trying to create the pdf was enough to fix the problem.