vendredi 8 mai 2015

How to download files with filename containing special characters using .Net WebClient

I am getting an error “400 – Bad Request” while using .Net WebClient to download files with filename containing certain characters:

For example if the file is named: 5L1XQE6FTest #.mp4 this generates an error.

If I remove the # sign the file is downloaded fine:

Here is my code:

  public ActionResult DownloadVideoFile(string filepath)
        {
            try
            {

               filepath = "http://localhost:1832/VideoUploads/" + filepath;
                var type = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                var path = Path.GetFileName(filepath);

                using (var client = new WebClient())
                {

                    var buffer = client.DownloadData(filepath);
                    return File(buffer, type.ToString(), path);
                }

            }
            catch (Exception e)
            {
                var test = e.Message;
            }
            return null;

        }

When I url encode the file name I still get the same error.

I have no control over the filename that I am trying to download as files are user submitted.

How can I resolve the Bad Request error while downloading files with special or reserved characters?

Aucun commentaire:

Enregistrer un commentaire