Share c# upload file to server

### Cách tải tệp lên máy chủ trong C#

Trong hướng dẫn này, bạn sẽ tìm hiểu cách tải tệp lên máy chủ bằng C#.Chúng tôi sẽ sử dụng [System.net.http.httpclient] (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient)yêu cầu đến máy chủ.

#### 1. Tạo một dự án mới

Đầu tiên, tạo một dự án C# mới trong Visual Studio.Bạn có thể sử dụng bất kỳ loại dự án nào, nhưng đối với hướng dẫn này, chúng tôi sẽ sử dụng dự án ứng dụng điều khiển ** **.

#### 2. Thêm gói Nuget

Tiếp theo, chúng ta cần thêm [System.net.http.webrequest] (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.webrequest) Gói Nuget vào dự án của chúng tôi.Gói này chứa các lớp mà chúng ta cần thực hiện yêu cầu ** đăng ** cho máy chủ.

Để thêm gói NUGET, hãy mở bảng điều khiển ** Trình quản lý gói ** và nhập lệnh sau:

`` `
Cài đặt-gói-hệ thống.net.http.webrequest
`` `

#### 3. Tạo một đối tượng httpclient

Bây giờ chúng tôi đã cài đặt gói Nuget, chúng tôi có thể tạo một đối tượng ** httpclient **.Đối tượng này sẽ được sử dụng để thực hiện yêu cầu ** bài đăng ** cho máy chủ.

Để tạo đối tượng ** httpclient **, hãy sử dụng mã sau:

`` `C#
var client = new httpClient ();
`` `

#### 4. Tạo một đối tượng formurlencodedContent

Bước tiếp theo là tạo một đối tượng ** formrlencodedContent **.Đối tượng này sẽ được sử dụng để tạo phần thân của yêu cầu ** **.

Để tạo đối tượng ** formUrLenCodedContent **, hãy sử dụng mã sau:

`` `C#
var nội dung = new FormUrLenCodedContent (new [] {
KeyValuePair mới <chuỗi, chuỗi> ("Tệp", @"C: \ path \ to \ file.txt")
});
`` `

Đối số đầu tiên cho trình xây dựng ** formUrLenCodedContent ** là một mảng của các đối tượng ** keyValuePair **.Mỗi ** KeyValuePair ** Đối tượng đại diện cho một cặp giá trị khóa sẽ được bao gồm trong phần thân của yêu cầu ** **.Trong trường hợp này, chúng tôi bao gồm một cặp giá trị khóa duy nhất với "tệp" khóa và giá trị của đường dẫn đến tệp mà chúng tôi muốn tải lên.

#### 5. Làm cho yêu cầu bài đăng

Bây giờ chúng tôi đã tạo một đối tượng ** httpclient ** và một đối tượng ** formrlencodedContent **, chúng tôi có thể thực hiện yêu cầu ** ** cho máy chủ.

Để thực hiện yêu cầu ** bài đăng **, hãy sử dụng mã sau:

`` `C#
var trả lời = Await client.postasync ("https://example.com/upload", nội dung);
`` `

Đối số đầu tiên cho phương thức ** postasync ** là URL của máy chủ mà chúng tôi muốn tải tệp lên.Đối số thứ hai là đối tượng ** formUrLenCodedContent ** mà chúng tôi đã tạo trong bước trước.

Phương thức ** postasync ** trả về một tác vụ ** ** đối tượng.Chúng ta có thể sử dụng từ khóa ** Await ** để chờ nhiệm vụ ** ** hoàn thành.

#### 6. Nhận phản hồi từ máy chủ

Khi yêu cầu ** bài đăng ** đã hoàn thành, chúng tôi có thể nhận được phản hồi từ máy chủ.

Để nhận được phản hồi, hãy sử dụng mã sau:

`` `C#
var result = Await phản hồi.Content.ReadAssTringAnync ();
`` `

Thuộc tính ** nội dung ** của đối tượng ** httpresponsemessage ** chứa phản hồi từ máy chủ.Chúng ta có thể sử dụng phương thức ** readasstringasync ** để đọc phản hồi dưới dạng chuỗi.

#### 7. In phản hồi cho bảng điều khiển

Cuối cùng, chúng ta có thể in phản hồi cho bảng điều khiển.

Để in phản hồi, sử dụng mã sau:

`` `C#
Console.WriteLine (result);
`` `

#### Ví dụ

Dưới đây là một ví dụ về chương trình C# hoàn chỉnh để tải tệp lên máy chủ:

`` `C#
sử dụng hệ thống;
sử dụng System.net.http;
sử dụng System.net.http.webrequest;
=======================================
### How to Upload a File to Server in C#

In this tutorial, you will learn how to upload a file to a server using C#. We will be using the [System.Net.Http.HttpClient](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) class to make a **POST** request to the server.

#### 1. Create a new project

First, create a new C# project in Visual Studio. You can use any type of project, but for this tutorial, we will be using a **Console Application** project.

#### 2. Add the NuGet package

Next, we need to add the [System.Net.Http.WebRequest](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.webrequest) NuGet package to our project. This package contains the classes that we need to make a **POST** request to the server.

To add the NuGet package, open the **Package Manager Console** and type the following command:

```
Install-Package System.Net.Http.WebRequest
```

#### 3. Create a HttpClient object

Now that we have the NuGet package installed, we can create a **HttpClient** object. This object will be used to make the **POST** request to the server.

To create a **HttpClient** object, use the following code:

```c#
var client = new HttpClient();
```

#### 4. Create a FormUrlEncodedContent object

The next step is to create a **FormUrlEncodedContent** object. This object will be used to create the body of the **POST** request.

To create a **FormUrlEncodedContent** object, use the following code:

```c#
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("file", @"C:\path\to\file.txt")
});
```

The first argument to the **FormUrlEncodedContent** constructor is an array of **KeyValuePair** objects. Each **KeyValuePair** object represents a key-value pair that will be included in the body of the **POST** request. In this case, we are including a single key-value pair with the key "file" and the value of the path to the file that we want to upload.

#### 5. Make the POST request

Now that we have created a **HttpClient** object and a **FormUrlEncodedContent** object, we can make the **POST** request to the server.

To make the **POST** request, use the following code:

```c#
var response = await client.PostAsync("https://example.com/upload", content);
```

The first argument to the **PostAsync** method is the URL of the server that we want to upload the file to. The second argument is the **FormUrlEncodedContent** object that we created in the previous step.

The **PostAsync** method returns a **Task** object. We can use the **await** keyword to wait for the **Task** to complete.

#### 6. Get the response from the server

Once the **POST** request has completed, we can get the response from the server.

To get the response, use the following code:

```c#
var result = await response.Content.ReadAsStringAsync();
```

The **Content** property of the **HttpResponseMessage** object contains the response from the server. We can use the **ReadAsStringAsync** method to read the response as a string.

#### 7. Print the response to the console

Finally, we can print the response to the console.

To print the response, use the following code:

```c#
Console.WriteLine(result);
```

#### Example

Here is an example of a complete C# program that uploads a file to a server:

```c#
using System;
using System.Net.Http;
using System.Net.Http.WebRequest;
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top