头盔程序员 2024-02-29 10:40 采纳率: 41.2%
浏览 4

C# 已知文件下载URL,如何在本地调用远程接口下载文件到本地指定目录?并返回消息类到本地

代码架构:c# webservice
已知文件下载URL,如何在本地调用远程接口下载文件到本地指定目录?并返回消息类到本地

  • 写回答

2条回答 默认 最新

  • Kwan的解忧杂货铺 Java领域优质创作者 2024-02-29 10:41
    关注

    头盔程序员 上午好☀️☀️☀️️
    本答案参考通义千问

    在 C# 中,你可以使用 HttpClient 类来下载文件,并通过 WebService 返回消息。以下是一个简单的示例,说明如何实现这个功能:

    using System;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    
    // 创建一个消息类,用于存储下载结果
    public class DownloadResult
    {
        public bool Success { get; set; }
        public string ErrorMessage { get; set; }
        public string FilePath { get; set; }
    }
    
    public class FileDownloader
    {
        private readonly HttpClient _httpClient;
        private readonly string _downloadDirectory;
    
        public FileDownloader(string downloadDirectory)
        {
            _httpClient = new HttpClient();
            _downloadDirectory = downloadDirectory;
        }
    
        // 下载文件的异步方法
        public async Task<DownloadResult> DownloadFileAsync(string url)
        {
            try
            {
                // 设置请求头(如果需要的话)
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Add("User-Agent", "Your User Agent");
    
                // 发送请求并获取响应
                HttpResponseMessage response = await _httpClient.SendAsync(request);
    
                // 检查响应状态码
                if (response.IsSuccessStatusCode)
                {
                    // 获取文件内容
                    byte[] content = await response.Content.ReadAsByteArrayAsync();
    
                    // 保存文件到本地
                    string fileName = Path.GetFileName(url);
                    string filePath = Path.Combine(_downloadDirectory, fileName);
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        fileStream.Write(content, 0, content.Length);
                    }
    
                    // 创建成功的结果对象
                    DownloadResult result = new DownloadResult
                    {
                        Success = true,
                        ErrorMessage = "",
                        FilePath = filePath
                    };
                    return result;
                }
                else
                {
                    // 处理错误情况
                    string errorMessage = $"Failed to download file. Status code: {response.StatusCode}";
                    DownloadResult result = new DownloadResult
                    {
                        Success = false,
                        ErrorMessage = errorMessage,
                        FilePath = null
                    };
                    return result;
                }
            }
            catch (Exception ex)
            {
                // 捕获和处理异常
                string errorMessage = $"Error downloading file: {ex.Message}";
                DownloadResult result = new DownloadResult
                {
                    Success = false,
                    ErrorMessage = errorMessage,
                    FilePath = null
                };
                return result;
            }
        }
    }
    
    // 在 WebService 中调用下载文件的方法
    public class YourWebService : WebService
    {
        [WebMethod]
        public DownloadResult DownloadFile(string url)
        {
            FileDownloader downloader = new FileDownloader("YourDownloadDirectory"); // 替换为你的本地目录
            return downloader.DownloadFileAsync(url).Result; // 注意这里使用了 blocking call,如果不想阻塞,可以使用 Task.Run 或 async/await
        }
    }
    

    解决方案步骤:

    1. 创建一个 DownloadResult 类,用于存储下载结果。
    2. 实现 FileDownloader 类,包含一个异步方法 DownloadFileAsync,它接收 URL,发送 HTTP 请求,检查响应状态码,保存文件到本地,并返回下载结果。
    3. 在 WebService 中创建一个方法,如 DownloadFile,实例化 FileDownloader 并调用其异步方法,然后返回结果。

    请注意,WebMethod 是针对 Web 服务的,如果你使用的是 WCF(Windows Communication Foundation)或 ASP.NET Core,则可能需要不同的实现方式。上述代码假设你正在使用传统的 ASP.NET Web 服务。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月29日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度