user2178640
user2178640

Reputation: 95

Upload File with .NET for Windows Store Apps

Now that I have come to the realization that I can not use the normal .NET to write my Windows Store apps, I am trying to wade through the mess that is .NET for Windows Store apps. My latest discovery is that the System.Net.WebClient class is missing, and I needed to use it to upload a file. Had this class been there, I would have done something along the lines of:

webClient.UploadFile("http://my.website/upload.php?a=" + someParam, "POST", filepath);

Unfortunately, I can't do this in .NET for windows store. How would I achieve a similar functionality using only .NET for windows store?

Upvotes: 1

Views: 1520

Answers (2)

Damir Arh
Damir Arh

Reputation: 17855

You first need to get reference to a StorageFile. Using FileOpenPicker would be one way:

var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".txt");
var file = await filePicker.PickSingleFileAsync();

Then use the following code to upload the file (I haven't tried it as I don't have an upload page handy, but it should work):

using (var randomStream = (await file.OpenReadAsync()))
{
    using (var stream = randomStream.AsStream())
    {
        using (var content = new StreamContent(stream))
        {
            var httpClient = new HttpClient();
            await httpClient.PostAsync(uri, content);
        }
    }
}

Upvotes: 0

Axarydax
Axarydax

Reputation: 16603

I'd try HttpClient class - http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx - it has Post method, and if you look at this answerenter link description here, it shows how to create multipart data for file upload.

Upvotes: 2

Related Questions