Having this in the VB.Net category when your code is C# wont help it get answered, its in the right place for it.
So WebClient is used to download files from a Web Service and its not clear thats what your trying to do with you code but if thats what you are doing then basically this is the code i use (i have removed my custom logging and error handling from the examples)
In my WebService i have this method - Here it is using the document id to get the doc path from the database, and then opening a File Stream of the file and returning it.
Code:
[Route("DownloadFile/{docid}")]
[HttpGet]
public HttpResponseMessage DownloadFile(string docid)
{
string filePath = data.GetDocumentPath(Int32.Parse(docid)).TrimEnd();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
In my website i have this method which calls the web service method and returns me the file from the server. The Files Directory is a folder i have created under the website location to which the application copies the downloaded file (you will need to set permissions on this folder when you host it in IIS so the IIS User or which ever user your running your app pool as, has write access to the folder)
Code:
public string DownloadFile(string docid, string FileName, string ext)
{
string webServiceUriFileDownload = "PutYourWebserviceURLHere";
try
{
using (var wc = new System.Net.WebClient())
{
string filepath = HttpContext.Current.Server.MapPath("~/Files/");
FileName = RemoveSpecialCharacters(FileName);
wc.DownloadFile(webServiceUriFileDownload + "/" + docid, @Path.Combine(filepath, FileName + "." + ext));
}
return FileName + "." + ext;
}
catch
{
return "";
}
}
Remove Special Characters method is used to remove any chars in the original document name that the web client download doesn't like (some chars are illegal and will stop the download) when creating the filename for the downloaded file.
Code:
public static string RemoveSpecialCharacters(string str)
{
Regex rgx = new Regex("[^a-zA-Z0-9_.-]+ ");
str = rgx.Replace(str, "");
return str;
}
Finally i take the full file path returned by that method and pass it in to this next one - which transmits the file as a download in the browser so the end user can open it or save it as they wish.
Code:
public void DownloadFile(string fileName)
{
try
{
Response.Clear();
System.IO.FileInfo file = new System.IO.FileInfo(Path.Combine(Server.MapPath("~/Files/"), fileName));
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.TransmitFile(file.FullName);
Response.End();
}
catch
{
}
}