c# ftp匿名登录并下载文件
时间: 2023-08-17 10:05:48 浏览: 66
你可以使用C#的FtpWebRequest类来实现FTP匿名登录并下载文件。下面是一个示例代码:
```csharp
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
string ftpUrl = "ftp://example.com/file.txt";
string localPath = "C:\\local\\file.txt";
try
{
// 创建FTP请求对象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("anonymous", "");
// 获取FTP服务器的响应
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
// 打开本地文件流
using (Stream stream = response.GetResponseStream())
{
// 创建本地文件
using (FileStream fileStream = new FileStream(localPath, FileMode.Create))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
// 从FTP服务器读取数据,并写入本地文件
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
}
}
Console.WriteLine("文件下载成功!");
}
catch (Exception ex)
{
Console.WriteLine("文件下载失败: " + ex.Message);
}
}
}
```
请将示例代码中的 `ftp://example.com/file.txt` 替换为实际的FTP服务器地址和文件路径,将 `C:\\local\\file.txt` 替换为本地保存文件的路径和文件名。这段代码会使用匿名登录凭据从FTP服务器下载文件,并将其保存到本地路径中。
注意:匿名登录是通过提供 "anonymous" 作为用户名和空字符串作为密码来实现的。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)