Certainly! Here are five sample code snippets in C# for uploading a file to a web service:
- Using
HttpClient
:
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public async Task UploadFileUsingHttpClient(string filePath, string uploadUrl)
{
using (HttpClient client = new HttpClient())
{
using (FileStream fileStream = File.OpenRead(filePath))
{
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
content.Add(new StreamContent(fileStream), "file", Path.GetFileName(filePath));
HttpResponseMessage response = await client.PostAsync(uploadUrl, content);
response.EnsureSuccessStatusCode();
}
}
}
}
- Using
WebClient
:
using System;
using System.Net;
using System.Threading.Tasks;
public void UploadFileUsingWebClient(string filePath, string uploadUrl)
{
using (WebClient client = new WebClient())
{
client.UploadFile(uploadUrl, filePath);
}
}
- Using
HttpWebRequest
:
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
public async Task UploadFileUsingHttpWebRequest(string filePath, string uploadUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl);
request.Method = "POST";
using (FileStream fileStream = File.OpenRead(filePath))
{
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await fileStream.CopyToAsync(requestStream);
requestStream.Close();
}
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// File uploaded successfully
}
}
}
- Using
RestSharp
:
using System;
using RestSharp;
public void UploadFileUsingRestSharp(string filePath, string uploadUrl)
{
RestClient client = new RestClient(uploadUrl);
RestRequest request = new RestRequest(Method.POST);
request.AddFile("file", filePath);
IRestResponse response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// File uploaded successfully
}
}
- Using
WebRequest
andStream
:
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
public async Task UploadFileUsingWebRequest(string filePath, string uploadUrl)
{
WebRequest request = WebRequest.Create(uploadUrl);
request.Method = "POST";
using (FileStream fileStream = File.OpenRead(filePath))
{
using (Stream requestStream = await request.GetRequestStreamAsync())
{
await fileStream.CopyToAsync(requestStream);
requestStream.Close();
}
}
using (WebResponse response = await request.GetResponseAsync())
{
// Handle the response if needed
}
}
Choose the code snippet that suits your needs and integrate it into your application. Remember to replace filePath
with the path of the file you want to upload and uploadUrl
with the URL of the web service endpoint to receive the file.