I have a web service, like this example for downloading a zip file from the server. When i open the URL through web browsers,I can download the zip file correctly. The problem is when I try to download the zip file through my desktop application. I use the following code to download:
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(#"http://localhost:9000/api/file/GetFile?filename=myPackage.zip"), #"myPackage.zip");
After testing this, I get the myPackage.zip downloaded, but it is empty, 0kb. Any help about this or any other server code + client code example?
You can try to use HttpClient instead. Usually, it is more convenient.
var client = new HttpClient();
var response = await client.GetAsync(#"http://localhost:9000/api/file/GetFile?filename=myPackage.zip");
using (var stream = await response.Content.ReadAsStreamAsync())
{
var fileInfo = new FileInfo("myPackage.zip");
using (var fileStream = fileInfo.OpenWrite())
{
await stream.CopyToAsync(fileStream);
}
}
Related
I'm trying to download a pdf file using a URL link to my computer, but it gives the following error:
'Unable to connect to the remote server' SocketException: A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond 41.180.70.243:80
I made sure that I can open the PDF in my browser when I use the link, and it works.
(I get the link from an XML response from another server).
I am using service references to integrate to another system using SOAP.
The result that I get back from the service is a XML file:
TPN_Test_ConsumerService.ConsumerSoapClient consumerServiceClient = new TPN_Test_ConsumerService.ConsumerSoapClient();
var result = consumerServiceClient.ConsumerEnquiry(securityInfo, moduleList, consumerBlock, enquiryBlock);
var PdfURL = "";
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(result));
XmlNodeList elemList = doc.GetElementsByTagName("PdfURL");
for (int i = 0; i < elemList.Count; i++)
{
PdfURL = elemList[i].InnerXml;
}
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
byte[] pdfBytes = client.DownloadData(PdfURL);
System.IO.File.WriteAllBytes("Path of file", pdfBytes);
I've tried setting the default proxy to false in the web.config file, but that also did not work.
You can download the PDF file and save it in Isolated Storage, to be able to view later offline.
So lets see how to do it step-by-step.
1- Download PDF file from a link( URL ) provided by server side:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));
2- Save the downloaded PDF file in local storage:
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storageFile.OpenFile("your-file.pdf", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
}
I am trying to download data from a blob:http link problem is the webclient complains about the url formating. blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518 this format is not know to webclient is there another way to download this data without using Azure calls?
using (var client = new WebClient())
{
//NotSupportedException: The URI prefix is not recognized.
var model = client.DownloadData(new Uri("blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518"));
//Also tried
var model = client.DownloadData("blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518");
}
I am working on a Windows to UWP app. A web service exists that when called (GET), returns a file. When the web service is triggered using a browser, it successfully downloads a file on the browser.
On the UWP app, I am using Windows.Web.Http to call the web service. I need to save get the file sent by the web service and save it on the device.
I currently have the following code. Not sure how to get the result from the web service and save to the file.
public async Task DownloadFile(string WebServiceURL, string PathToSave)
{
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
{
//not sure if this is correct and if it is, how to save this to a file
}
}
Using System.Web.Http, I am able to easily do this using the following:
Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();
However, using Windows.Web.Http, I am not sure how I can do this. Please help!
this what you looking for?
like this?
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
//not sure if this is correct and if it is, how to save this to a file
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await result.Content.WriteToStreamAsync(filestream);
await filestream.FlushAsync();
}
I am using "webclient" to download and save a file by url in windows application.
here is my code:
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Cookie, cc);
wc.DownloadFile(new Uri(e.Url.ToString()), targetPath);
this is working fine local system.(downloading the file and saved to target path automatically with out showing any popup).
But when i am trying to execute the .exe in server its showing save/open popup.
Is there any modifications require to download a file in server settings.
Please help me to download the file with out showing popup in server too.
thanks in advance..
Finally i got the solution for this issue..
herw the code:
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Cookie, cc);
using (Stream data = wc.OpenRead(new Uri(e.Url.ToString())))
{
using (Stream targetfile = File.Create(targetPath))
{
data.CopyTo(targetfile);
}
}
here i just replaced the code
wc.DownloadFile(new Uri(e.Url.ToString()), targetPath);
with the blow lines:
using (Stream data = wc.OpenRead(new Uri(e.Url.ToString())))
{
using (Stream targetfile = File.Create(targetPath))
{
data.CopyTo(targetfile);
}
}
Now its working fine..
Thanks all for ur response..
I am trying to download image from <img src="...">.
If the src contains the file name and extension, I can download image simply passing url to my program.
However, when the src does not contains file name and extension, like
<img style="-webkit-user-select: none; cursor: zoom-in;" src="https://secure.somewebsite.net/website/member.php/1/folders/get_attach?mail_id=11111&attach_id=1">
it is possible to download the image from C# code?
Thank you.
Here is a complete sample
using (WebClient client = new WebClient())
{
client.DownloadFile("http://somedomain/image.png",
#"c:\temp\image.png");
// You can also you the async call
client.DownloadFileAsync("http://somedomain/image.png",
#"c:\temp\image.png");
}
Yes it is possible,
You can use these methods to download the image from c# :
client.DownloadFileAsync(new Uri(url), #"c:\temp\img.png");
client.DownloadFile(new Uri(url), #"c:\temp\img.png");
Now, WebClient is obselete (-> https://learn.microsoft.com/en-us/dotnet/fundamentals/syslib-diagnostics/syslib0014)
use for exemple
using var httpClient = new HttpClient();
var streamGot = await httpClient.GetStreamAsync("http://somedomain/image.png");
await using var fileStream = new FileStream("img.png", FileMode.Create, FileAccess.Write);
streamGot.CopyTo(fileStream);