How can I download file in xamarin with webview? - c#

I'm new in a Xamarin development. I hope that you can resolve my problem in a simple mode.
I've a crossplatform app developed with Xamarin and I want to download a file from a url.
I tried to download file using C# code but i can't do it (for crossplatform app) so I want to try other way. I want to use a webview and download the file directly into the web view. the problem is that when i click the button "download" into the webview it do anything. can you help me in a simply way?
my webview is this:
<WebView Source="https://download.cnet.com/Free-YouTube-Downloader/3001-2071_4-75219434.html/" x:Name="webv" WidthRequest="1000" HeightRequest="1000" />
it is an example of url

You have some plenty choices. But here's 2 of them. It's a simple one.
Using Device.OpenUri(new Uri("Download link here")).
This method is simple. It open the URL in client mobile web browser. And from there, the web browser will handle the background worker for download progress.
Using WebClient() class. Using this class, you'll can have your response in data type that you like maybe string or byte[]. Below's the sample:
var wb = new WebClient();
//Download as string
string x = wb.DownloadString("Download url");
//Download as byte[]
byte[] x = wb.DownloadData("Download Url");
From the return value of x, now you can rewrite it using System.IO to another file.
Note: These method is just basic. You can implement it in task, so your app will not hanging up while the download is in process.
Better approach: Via dependency service, download file from the native Android & iOS itself via interface class. you can check this one out: https://github.com/SimonSimCity/Xamarin-CrossDownloadManager#where-are-the-files-stored

Related

Accessing downloaded file instead of page HTML

I have some code that connects to an HTTP API, and is supposed to get an XML response. When the API link is placed in a browser, the browser downloads the XML as a file. However, when the code connects to the same API, HTML is returned. I've told the API owner but they don't think anything is wrong. Is there a way to capture the downloaded file instead of the HTML?
I've tried setting the headers to make my code look like a browser. Also tried using WebRequest instead of WebClient. But nothing works.
Here is the code, the URL works in the browser (file downloaded) but doesn't work for WebClient:
WebClient webClient = new WebClient();
string result = webClient.DownloadString(url);
The code should somehow get the XML file instead of the page HTML (actually the HTML doesn't appear in the browser, only the file).
The uri that you access may be a HTML page that have its own mechanism (like generating the actual download address which may be dynamically generated by the server and redirecting to it, in order to prevent external linking access) to access the real file.
It is supposed to use a browser background browser core like CefSharp to run the HTML and its javascript to let it navigate, and probably you may want to hook the download event to handle the downloading.
I think you need to add accept header to the WebClient object.
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.Accept] = "application/xml;q=1";
string result = webClient.DownloadString(url);
}
Thank you all for your input. In the end, it was caused by our vendor switching to TLS 1.2. I just had to force my code to use 1.2 and then it worked.

How to Save Web page as html file using C# in UWP?

I was working on a uwp project which uses webview to display webpages. I want to save a webpage locally from a url. I tried few these how to save the webpage using c#?
But it doesn't seem to be working as the solution is for a basic windows form app.
Please, forgive if I made any mistake asking question as I'm totally new to stackoverflow.
I want to save a webpage locally from a url.
It is similar to windows form. Try to send get request to the URL, and get the buffer or HTML content. For sending get request, you could use HttpClient. And then save the html buffer to a local file which format is .html. For example:
HttpClient httpclient = new HttpClient();
var result = await httpclient.GetBufferAsync(new Uri("https://www.microsoft.com/en-sg/"));
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("test2.html", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBufferAsync(file, result);
After downloaded you may find the downloaded file in C:\Users\{username}\AppData\Local\Packages\{PackageId}\LocalState.
For more details about file operations please reference Files, folders, and libraries.

Saving Data from phone to a OnceDrive account

Currently have no experience in programming and have been chucked in the deep end. I've currently made a simple UWP app that has a text box and a button. I want it so when I type in the text box and hit the button, the content from that text box is stored into a onedrive account as a text file. currently I have thee layout done and I've double clicked the button to enter the cose but I don't know what else to do and I havent had much luck with googling around. Any help or solutions? Thanks!
We can use OneDrive API to do this in UWP apps. This is a modern REST API and based on this API there are some OneDrive SDKs for different platforms to quickly start using the OneDrive API without the need to get into all the details of authentication, JSON parsing, HTTP connections and more. As you are using C#, OneDrive SDK for C# is strongly recommended.
For more info about how to use this SDK in UWP apps, please see Getting started and Documentation and resources on GitHub and also the article: Windows 10 - Implementing a UWP App with the Official OneDrive SDK.
Following is a simple sample. In the sample, I used OneDrive's App Folder, this folder is a dedicated, special folder for your app. It is typically named after your app, and is found in the Apps folder in the user's OneDrive. If you request the onedrive.appfolder permission scope and the user authorizes it, your app gets read and write access to this folder.
private async void Button_Click(object sender, RoutedEventArgs e)
{
var oneDriveClient = await OneDriveClientExtensions.GetAuthenticatedUniversalClient(new[] { "onedrive.appfolder" });
using (var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(textBox.Text)))
{
var item = await oneDriveClient.Drive.Special.AppRoot.ItemWithPath("backup.txt").Content.Request().PutAsync<Item>(contentStream);
}
}

How to get the WebService address dynamically from the txt file in Windows Forms

I'm building a small application and I'm using WebService in it. I was using a local WebService just by adding its reference in my project's solution manager.
My question is: is it possible to get the WebService url address dynamically, for example from a .txt file?
Thanks for every help.
Edit:
I want to change the WebService url address in my app's code. After that, the url will be placed in a .txt file and the app will get it from there.
You can set any url for your WebService client using the clients constructor. There you can provide the url to use:
var client = new YourServiceClient("<bindingName>", new EndpointAddress("<your url>"));
Please check solution here. They are accessing the URL from config file, instead of text while.

How to programatically upload/post an image to an image hosting website without a browser?

I want to write a simple utility to upload images to various free image hosting websites like TinyPic or Imageshack via a right-click context menu for the file.
How can I do this using .NET? I've seen some linux scripts that use cURL to post images to these website but I'm not sure how I could create the post request, complete with an image in C#?
Can someone point me in the right direction?
EDIT:
I've found a pretty good resource. Cropper, a free screenshot tool written in .net, has a lot of open-source plugins. One of them is a SendToTinyPic.. complete with source. Link here:
http://www.codeplex.com/cropperplugins
The FlickrNet API makes this extremely easy for working with Flickr from .NET. You have to have a Flickr account as well as an API key and shared secret. Once you have what you need, working with the API is very simple:
// http://www.flickr.com/services/api/misc.api_keys.html
string flickrApiKey = "<api key>";
string flickrApiSharedSecret = "<shared secret>";
string flickrAuthenticationToken = "<authentication token>";
Flickr flickr = new Flickr( flickrApiKey, flickrApiSharedSecret );
flickr.AuthToken = flickrAuthenticationToken;
foreach ( FileInfo image in new FileInfo[] {
new FileInfo( #"C:\image1.jpg" ),
new FileInfo( #"C:\image2.jpg" ) } )
{
string photoId = flickr.UploadPicture(
image.FullName, image.Name, image.Name, "tag1, tag2" );
}
Use HttpWebRequest.
Using this class, you can POST data to a remote HTTP address, just set the mime/type to multi-part/form encoded, and post the binary data from the image with the request.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(VS.71).aspx
For ImageShack, take a look to this Application.
TinyPic.com doesn't have an API as far as I know, but the Cropper SendToTinyPic Plugin tries to upload using "Screen scraping". The official version of the plugin doesn't work right now, but I put together a patch using the same approach, and submitted it to the cropperplugins project. It's just one source module that changed. Anyone can download the plugins project, and then drop in my patch and it should work.
With the patch, it's PritScrn or Alt-PrntScrn will save the image and upload to tinypic, and stuff the URL of the raw image on your clipboard. All in 2 seconds. easy.
If you don't want the actual tool, you can still look at the source code of my patch to see how to POST a page with form-data and a file upload. No direct link. See http://cropperplugins.codeplex.com/SourceControl/PatchList.aspx and look for #3239.
This example image was produced and then auto-uploaded to tinypic.com with the Alt-PrtScrn key-combo.
To embed it here, I just had to ctrl-V because the URL is stored on the clipboard.

Categories