在 C# 中,可以使用异步方法将大文件写入网络流,以提高效率并避免阻塞主线程。以下是一个示例代码,展示如何将大文件异步上传到网络:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string filePath = 'path_to_large_file';
        string url = 'http://example.com/upload';

        await UploadFileAsync(filePath, url);
    }

    static async Task UploadFileAsync(string filePath, string url)
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
        {
            using (HttpClient client = new HttpClient())
            {
                using (StreamContent fileContent = new StreamContent(fileStream))
                {
                    using (MultipartFormDataContent formData = new MultipartFormDataContent())
                    {
                        formData.Add(fileContent, 'file', Path.GetFileName(filePath));

                        HttpResponseMessage response = await client.PostAsync(url, formData);

                        if (response.IsSuccessStatusCode)
                        {                            
                            Console.WriteLine('File uploaded successfully.');
                        }
                        else
                        {
                            Console.WriteLine('File upload failed.');
                        }
                    }
                }
            }
        }
    }
}

在上面的示例中,我们使用 HttpClient 类将文件异步地上传到指定的 URL。首先,我们打开一个文件流来读取要上传的大文件。然后,我们创建一个 HttpClient 实例,并使用 StreamContent 将文件内容添加到 MultipartFormDataContent 中。最后,我们使用 PostAsync 方法将该内容上传到指定的 URL,并根据响应状态代码判断上传是否成功。

请注意,上述示例中的代码需要使用 using 语句来确保流和客户端资源在使用后正确释放。这是为了避免资源泄漏,尤其是在处理大文件时更为重要。

C# 异步上传大文件到网络流 - 代码示例

原文地址: https://www.cveoy.top/t/topic/pfWK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录