Smeegs
Smeegs

Reputation: 9224

How do I save an image url to a local file in Windows 8 c#

Basically, the app displays images, and I want the user to be able to select an image for download and store it locally.

I have the URL, but I don't know how to use that url in conjunction with the filepicker.

Upvotes: 2

Views: 2373

Answers (3)

Damir Arh
Damir Arh

Reputation: 17855

You can use the following method to download the file from a given Uri to a file selected with a file picker:

private async Task<StorageFile> SaveUriToFile(string uri)
{
    var picker = new FileSavePicker();

    // set appropriate file types
    picker.FileTypeChoices.Add(".jpg Image", new List<string> { ".jpg" });
    picker.DefaultFileExtension = ".jpg";

    var file = await picker.PickSaveFileAsync();
    using (var fileStream = await file.OpenStreamForWriteAsync())
    {
        var client = new HttpClient();
        var httpStream = await client.GetStreamAsync(uri);
        await httpStream.CopyToAsync(fileStream);
        fileStream.Dispose();
    }
    return file;
}

Upvotes: 4

Haedrian
Haedrian

Reputation: 4328

SaveFileDialog myFilePicker = new SaveFileDialog();

//put options here like filters or whatever

if (myFilePicker.ShowDialog() == DialogResult.OK)
{
    WebClient webClient = new WebClient();
    webClient.DownloadFile("http://example.com/picture.jpg", myFilePicker.SelectedFile);
}

Upvotes: -1

Fixus
Fixus

Reputation: 4641

I think you can always read the file as a stream and save it bit by bit on the local machine. But I need to say that I've done this many times in JAVA, I never needed to check this in C# :)

Upvotes: 0

Related Questions