确定目录存在
using System.Net;
/// <summary>
/// 确定ftp当前目录存在
/// </summary>
/// <param name="dir"></param>
private void FtpDirectoryExit(string dir)
{
if (!dir.EndsWith("/"))
{
dir += "/";
}
var req = (FtpWebRequest)WebRequest.Create(dir);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
req.Credentials = new NetworkCredential(_user, _password);
using var response = (FtpWebResponse)req.GetResponse();
Console.WriteLine("FtpCreateDirectory: " + dir);
}
文件上传
/// <summary>
/// 文件上传
/// </summary>
/// <param name="path">本地路径</param>
/// <returns></returns>
private Upload(string path)
{
try
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(_user, _password);
string fileName = Path.GetFileName(path);
var url = Path.Combine(_rootUrl, DateTime.Now.ToString("yy/MM/dd/HHmmssfff"), fileName);
var uri = new Uri(url);
client.UploadProgressChanged += Client_UploadProgressChanged;
client.UploadFileCompleted += Client_UploadFileCompleted;
client.UploadFileAsync(uri, fileName);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void Client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine($"{e.BytesSent}/{e.ProgressPercentage}");
}
private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
if (!e.Cancelled)
{
Console.WriteLine("上传成功!");
}
}