C#访问远程服务器共享目录下载文件到本地
时间: 2024-11-13 10:25:17 浏览: 44
在C#中,你可以使用命名管道、Web服务、WCF(Windows Communication Foundation)或者HTTP客户端库如HttpClient来访问远程服务器并下载文件。这里以HttpClient为例说明:
```csharp
using System;
using System.Net.Http;
using System.IO;
public async void DownloadFileFromServer(string remoteFilePath, string localPath)
{
try
{
using HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(remoteFilePath);
if (response.IsSuccessStatusCode)
{
byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
using FileStream localFileStream = new FileStream(localPath, FileMode.Create);
await localFileStream.WriteAsync(fileBytes, 0, fileBytes.Length);
Console.WriteLine($"成功将文件从服务器下载至本地: {localPath}");
}
else
{
Console.WriteLine($"下载文件失败,状态码: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"下载文件时发生异常: {ex.Message}");
}
}
```
在这个示例中,你需要提供远程文件的URL(`remoteFilePath`),以及你想保存文件的本地路径(`localPath`)。调用`DownloadFileFromServer`方法时传入这两个参数即可。
阅读全文