C# WebClient进行FTP服务上传文件和下载文件
2021-07-19 00:20
定义WebClient使用的操作类: 操作类名称WebUpDown
WebClient上传文件至Ftp服务:
////
/// WebClient上传文件至Ftp服务
///
/// 文件名,全路径格式
/// 服务器文件夹路径
public static void UpLoadFile(string fileNamePath, string uriString)
{
string NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
uriString = uriString + NewFileName;
//创建WebClient实例
WebClient myWebClient = new WebClient();
//指定用户名和密码
myWebClient.Credentials = new NetworkCredential("username", "password");
try
{
//上传文件
myWebClient.UploadFile(new Uri(uriString), fileNamePath);
}
catch (Exception ex)
{
MessageBox.Show("文件上传失败,失败原因:" + ex.Message);
}
finally
{
myWebClient.Dispose();
}
}
下载服务器文件至客户端:
///
/// 下载服务器文件至客户端
///
/// 被下载的文件地址,绝对路径
/// 另存放的目录
public static void Download(string URL, string Dir)
{
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username "," password ");
string Path = Dir; //另存为的绝对路径+文件名
try
{
client.DownloadFile(new Uri(URL), Path);
}
catch (Exception ex)
{
MessageBox.Show("文件下载失败,失败原因:" + ex.Message);
}
finally
{
client.Dispose();
}
}
调用方法:
///
/// WebClient上传到Ftp服务
///
///
///
private void Button_Click_5(object sender, RoutedEventArgs e)
{
WebUpDown.UpLoadFile(@"C:\123.txt",@"ftp://localhost//");
}
///
/// WebClient使用Ftp服务下载到客户端
///
///
///
private void Button_Click_6(object sender, RoutedEventArgs e)
{
WebUpDown.Download(@"ftp://localhost//123.txt", @"C:\123.txt");
}
上一篇:HTML-JS-CODING
文章标题:C# WebClient进行FTP服务上传文件和下载文件
文章链接:http://soscw.com/index.php/essay/106260.html