c# WPF 不同窗口,调用一个文件类,定义方法通过Http从远程服务下载某个文件夹的所有图片或某个图片
时间: 2024-09-21 10:11:58 浏览: 59
WPF C# 文件夹复制,文件复制
5星 · 资源好评率100%
在C#的WPF应用程序中,如果你想要在一个主窗口或其他窗口中调用一个专门负责处理HTTP请求的文件类,以便从远程服务器下载文件夹中的所有图片或特定图片,可以按照以下步骤操作:
1. **创建一个文件类**(例如`FileDownloader.cs`):
```csharp
using System;
using System.IO;
using System.Net.Http;
public class FileDownloader
{
private readonly HttpClient _httpClient;
public FileDownloader()
{
_httpClient = new HttpClient();
}
// 定义公共方法下载目录下的所有图片
public async Task DownloadDirectoryAsync(string url)
{
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string imageUrlPattern = $"{url}/*.{jpg|png|gif}"; // 根据需要调整图片格式
await DownloadFilesFromPattern(imageUrlPattern);
}
else
{
Console.WriteLine($"Failed to fetch directory. Status code: {response.StatusCode}");
}
}
// 私有方法下载符合模式的图片
private async Task DownloadFilesFromPattern(string pattern)
{
try
{
var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, pattern));
using var content = await response.Content.ReadAsStreamAsync();
if (content != null)
{
await SaveToDiskAsync(content);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error downloading files: {ex.Message}");
}
}
// 将响应内容保存到本地磁盘的方法
private async Task SaveToDiskAsync(Stream inputStream)
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Downloads"); // 获取应用安装路径的Download子目录
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputStream.Name);
string fullFileName = Path.Combine(filePath, fileNameWithoutExtension);
using (var outputStream = File.Create(fullFileName))
{
await inputStream.CopyToAsync(outputStream);
}
}
}
```
2. **在需要调用该类的窗口上使用它**:
在你的WPF窗口类(如`MainWindow.xaml.cs`)中,注入`FileDownloader`实例并调用其方法:
```csharp
public partial class MainWindow : Window
{
private readonly FileDownloader _fileDownloader;
public MainWindow()
{
InitializeComponent();
_fileDownloader = new FileDownloader(); // 创建下载器实例
// 想要在点击按钮或满足某个条件时开始下载,添加事件处理
Button downloadButton = FindResource("YourDownloadButton") as Button; // 替换"YourDownloadButton"为你的按钮名
downloadButton.Click += DownloadButton_Click;
}
private async void DownloadButton_Click(object sender, RoutedEventArgs e)
{
string remoteFolderPath = "http://yourremote/folder/"; // 远程文件夹URL
await _fileDownloader.DownloadDirectoryAsync(remoteFolderPath);
}
}
阅读全文