UploadStringAsync Method
Asynchronously uploads a string to a resource identified by a URI.
public void UploadStringAsync(Uri address, string data);public void UploadStringAsync(string address, string data);public void UploadStringAsync(Uri address, string method, string data);public void UploadStringAsync(string address, string method, string data);public void UploadStringAsync(Uri address, string method, string data, object userToken);public void UploadStringAsync(string address, string method, string data, object userToken);
Parameters
| Parameter | Description |
|---|---|
address |
The URI to upload data to. |
method |
The HTTP method to use for the upload (e.g., POST or PUT). |
data |
The string to upload. |
userToken |
An optional object that distinguishes this asynchronous operation from other operations. |
Return Value
This method does not return a value.
Exceptions
| Exception Type | Condition |
|---|---|
ArgumentNullException |
address is null. |
ArgumentNullException |
data is null. |
ArgumentException |
method is not a valid HTTP method. |
Remarks
The UploadStringAsync method uploads the specified string to the server. This is an asynchronous operation, meaning that the calling thread is not blocked while the upload is in progress. You can use the UploadStringCompletedEventHandler delegate to receive notifications when the operation completes.
The userToken parameter can be used to track asynchronous requests. For example, you can pass an identifier to the userToken parameter to associate the request with a specific UI element or data object.
Example
using System;
using System.Net;
using System.Threading.Tasks;
public class UploadStringExample
{
public static async Task UploadDataAsync()
{
using (WebClient client = new WebClient())
{
string uri = "http://example.com/upload";
string dataToUpload = "This is the string data to be uploaded.";
client.UploadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
Console.WriteLine($"Upload successful. Response: {e.Result}");
}
else
{
Console.WriteLine($"Error uploading: {e.Error.Message}");
}
};
Console.WriteLine("Starting string upload...");
client.UploadStringAsync(uri, dataToUpload);
}
}
public static async Task Main(string[] args)
{
await UploadDataAsync();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}