using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.IO; using System.Net; using DicomTool.Model; namespace DicomTool { public static class FtpHelper { public static void DownloadFtpFile(List ftpUriList, string username, string password, string localFilePath) { // 确保本地文件路径是目录 if (!Directory.Exists(localFilePath)) { Directory.CreateDirectory(localFilePath); } foreach (var reportEcg in ftpUriList) { // 创建 FtpWebRequest 对象 var request = (FtpWebRequest)WebRequest.Create(reportEcg.ReportUrl); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); try { // 获取响应并读取数据 var response = (FtpWebResponse)request.GetResponse(); var responseStream = response.GetResponseStream(); // 获取文件名 // string fileName = Path.GetFileName(new Uri(reportEcg.ReportUrl).LocalPath); var fileName = reportEcg.ID + ".jpg"; Console.WriteLine("【下载】"+ reportEcg.ID + ".jpg"); var localFileFullPath = Path.Combine(localFilePath, fileName); // 将 FTP 文件内容写入本地文件 using (FileStream fileStream = new FileStream(localFileFullPath, FileMode.Create, FileAccess.Write)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0) { fileStream.Write(buffer, 0, bytesRead); } } responseStream.Close(); response.Close(); } catch (WebException ex) { // 处理异常,例如打印错误信息 Console.WriteLine("Download failed for " + reportEcg + ": " + ex.Message); } } } } }