user2837961 user2837961 - 2 months ago 12
ASP.NET (C#) Question

File Path in WebClient

In my asp.net application, I am writing a file in code behind. I then want to use this file as below into a Handler but I get an error 'Illegal characters in Path'. I can't understand why? Help please.

The value of files in below is "306963020170816111848_Generic_P.pdf" and the file definitely exists in the correct path

WebClient client = new WebClient();
client.DownloadString(@"Handlers/MyPrintPdf.ashx?PdfFile=" + Server.MapPath("~/Templates/MyFiles/" + files)); // error here


Changed to use

HttpUtility.UrlEncode(@"Handlers/MyPrintPdf.ashx?PdfFile=" + Server.MapPath("~/Templates/MyFiles/" + files));

Answer Source

You should use the Uri overload of your DownloadString method. These parameters must be url encoded.

EDIT:
HttpUtility.UrlEncode(url)should also work.