简体   繁体   中英

Reading files to bytes not working properly in project

I have a weird problem. I am making a C# MVC application which generates PDF's and offers them for download with a download button.

public ActionResult Download()
{
    string url = (string)TempData["url"];

    byte[] thePdf = System.IO.File.ReadAllBytes(url);

    return File(thePdf, "application/pdf");
}

All of a sudden I can't properly convert a PDF file to byte[] , either with File.ReadAllBytes() or with a MemoryStream (or any other stream).

When I used a MemoryStream I got an InvalidOperationException on both the ReadTimeOut and WriteTimeOut .

I implemented the code mentioned above in a new C# MVC Project and there everything worked fine. So the issue must be with the project that i'm working in.

If your url is remote url, you should use WebClient to download data like below.

I tried to reproduce your code and it worked.

 public ActionResult Download()
        {
            string url = (string)TempData["url"];

            url = "http://www.iuh.edu.vn/Tuyensinh/QC/TomTatQuyCheThiTHPT2018.pdf";

            using (var client = new WebClient())
            {
                // read data
                byte[] thePdf = client.DownloadData(url);

                return File(thePdf, "application/pdf");

            }

            //byte[] thePdf = System.IO.File.ReadAllBytes(url);

            //return File(thePdf, "application/pdf");
        }

In cshtml:

<input type="button" value="Download" onclick="window.location.href='/YourController/Download'" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM