c# ftp helper sample code
Here's a sample code for a C# FTP helper class that can upload and download files:
using System;
using System.IO;
using System.Net;
namespace FtpHelper
{
public class FtpClient
{
private readonly string _host;
private readonly string _username;
private readonly string _password;
public FtpClient(string host, string username, string password)
{
_host = host;
_username = username;
_password = password;
}
public void UploadFile(string localFilePath, string remoteFilePath)
{
var request = (FtpWebRequest)WebRequest.Create($"ftp://{_host}/{remoteFilePath}");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_username, _password);
using (var fileStream = File.OpenRead(localFilePath))
using (var ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
}
public void DownloadFile(string remoteFilePath, string localFilePath)
{
var request = (FtpWebRequest)WebRequest.Create($"ftp://{_host}/{remoteFilePath}");
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_username, _password);
using (var response = (FtpWebResponse)request.GetResponse())
using (var ftpStream = response.GetResponseStream())
using (var fileStream = File.Create(localFilePath))
{
ftpStream.CopyTo(fileStream);
}
}
}
}
To use the class, simply create a new instance of FtpClient with your FTP hostname, username, and password, and then call the UploadFile or DownloadFile method:
var ftpClient = new FtpClient("ftp.example.com", "username", "password");
ftpClient.UploadFile("localfile.txt", "remotefile.txt");
ftpClient.DownloadFile("remotefile.txt", "localfile.txt");
``
原文地址: https://www.cveoy.top/t/topic/dxDj 著作权归作者所有。请勿转载和采集!