Reputation: 17280
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;
}
I have no control over the filename that I am trying to download as files are user submitted.
When I Url encode the file I get a "Cannot find file" error:
using (var client = new WebClient())
{
filepath = Url.Encode(filepath);
var buffer = client.DownloadData(filepath);
return File(buffer, type.ToString(), path);
}
Here is the path after URL encoding:
C:\Program Files (x86)\IIS Express\http%3a%2f%2flocalhost%3a1832%2fVideoUploads%2f5L1XQE6FTest+%23.mp4'
How can I resolve the Bad Request error while downloading files with special or reserved characters?
Upvotes: 0
Views: 3996
Reputation: 239460
At what point in your code is the exception actually being raised? WebClient
should have no problem downloading any validly named resource (valid as in it actually functions as a URL). If the URL you're trying to use is in fact not a valid URL (because of the odd file name), URL encoding it might be sufficient to fix the issue.
However, you're also using the bad file name later as a parameter to File
, and that's probably a bad idea. If this is where the exception is being raised, simply constructing your own filename, without the problematic characters, should be enough to solve the problem.
Upvotes: 1