0

I am saving my files in the folder in my web form project /Upload/Secret/ and its saved correct. and i save the file name in database. I am try to view the files which is pdf and i created new item to my project .dbml and i drag and drop my table on that item. Now when i press the link button to view my file this error appeared : Could not find a part of the path.

I got this code from youtube https://www.youtube.com/watch?v=h7sswv6LyIw

protected void linkfilebtn_Click1(object sender, EventArgs e)
        {
            int Rowindex = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
            string filelocation = DGDEPT.Rows[Rowindex].Cells[3].Text;
            string filepath = Server.MapPath("~/Upload/Secret/" + filelocation);

            WebClient user = new WebClient();
            Byte[] filebuffer = user.DownloadData(filepath);

            if (filebuffer != null)
            {
                Response.ContentType = ("application/pdf");
                Response.AddHeader("content-length", filebuffer.Length.ToString());
                Response.BinaryWrite(filebuffer);
            }
        }

the expected result view the pdf file but the actual it shows me error in this line

Byte[] filebuffer = user.DownloadData(filepath);

where is the error ?

Abdullah
  • 983
  • 12
  • 26
  • 2
    What is the **exact** value of `filepath`? – mjwills Jan 19 '19 at 12:47
  • Possible duplicate of [Using WebClient to access local files](https://stackoverflow.com/questions/13074555/using-webclient-to-access-local-files) – mjwills Jan 19 '19 at 12:48
  • Why are you using `WebClient` to load local files? I mean you can, if you want (see my duplicate), but it is a bit weird. – mjwills Jan 19 '19 at 13:06
  • Actually i want to view the pdf file only after save it and i found this way in youtube i dont use Webclient before and i tried a lot to view pdf file in my application before but cannot find a way to view pdf files in my application I will try your link. – Abdullah Jan 19 '19 at 13:26
  • I tried the physical file location and its working Byte[] filebuffer = user.DownloadData("D:\\Directorate-website\\Directorate\\Directorate\\Upload\\Secret\\D7366.pdf"); but with filepath string variable not working? – Abdullah Jan 19 '19 at 13:46
  • @mjwills can you show me how to update my code and use your solution public byte[] Load(string fileName) { Uri uri = new Uri(fileName); var client = new WebClient(); return client.DownloadData(uri); } – Abdullah Jan 19 '19 at 14:11

1 Answers1

1

There's no reason to "download" the file from your pc with a WebClient, directly read it as a file instead by replacing

WebClient user = new WebClient();
Byte[] filebuffer = user.DownloadData(filepath);

With

Byte[] filebuffer = System.IO.File.ReadAllBytes(filepath);
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78