C#自定义FTP访问类的代码

如下资料是关于C#自定义FTP访问类的代码,应该对各朋友有帮助。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace DotNet.Utilities
{
public class FTPHelper
{
#region 字段
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
string ftpRemotePath;
#endregion

public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
}

public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public void Download(string filePath, string fileName)
{
try
{
FileStream outputStream = new FileStream(filePath + "\" + fileName, FileMode.Create);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public void Delete(string fileName)
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public string[] GetFilesDetailList()
{
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("n"), 1);
reader.Close();
response.Close();
return result.ToString().Split(‘n‘);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

private string[] GetAllList(string url)
{
List<string> list = new List<string>();
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
req.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
req.UsePassive = true;
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
list.Add(s);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return list.ToArray();
}

public string[] GetFileList(string url)
{
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{

if (line.IndexOf("<DIR>") == -1)
{
result.Append(Regex.Match(line, @"[S]+ [S]+", RegexOptions.IgnoreCase).Value.Split(‘ ‘)[1]);
result.Append("n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf(‘n‘), 1);
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw (ex);
}
return result.ToString().Split(‘n‘);
}

public bool FileExist(string RemoteFileName)
{
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
}

public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
}

public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
return fileSize;
}

public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
}

public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}

public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
{
ftpRemotePath = DirectoryName;
}
else
{
ftpRemotePath += DirectoryName + "/";
}
}
}
}

原文地址:https://www.cnblogs.com/javahouse/p/10308242.html

时间: 2024-10-10 11:00:37

C#自定义FTP访问类的代码的相关文章

自定义一个异常类模板代码实例

一:自定义异常类: package 自定义异常; //或者继承RuntimeException(运行时异常) public class MyException extends Exception { private static final long serialVersionUID = 1L; // 提供无参数的构造方法 public MyException() { } // 提供一个有参数的构造方法 public MyException(String message) { super(mes

SSIS 学习之旅 FTP访问类

这章把脚本任务访问FTP的方法 全部给大家. 控件的使用大家如果有不懂得可以看下我之前的文章.第一章:SSIS 学习之旅 第一个SSIS 示例(一)(上) 第二章:SSIS 学习之旅 第一个SSIS 示例(二) 第三章:SSIS 学习之旅 数据同步 第四章:SSIS 学习之旅 FTP文件传输-FTP任务 第五章:SSIS 学习之旅 FTP文件传输-脚本任务 #region 连接FTP服务器 /// <summary> /// 连接FTP服务器 /// </summary> ///

C#-ade.net-实体类、数据访问类

实体类.数据访问类 是由封装演变而来,使对数据的访问更便捷,使用时只需要调用即可,无需再次编写代码 实体类是按照数据库表的结构封装起来的一个类 首先,新建文件夹 App_Code ,用于存放数据库类等类文件,新建类,例如: Users(与数据库访问的表同名)和 UsersData 在类UsersData里写数据库访问方法 using System; using System.Collections.Generic; using System.Linq; using System.Text; us

1,OC语言的前世今生 ,2,OC语言入门,3,OC语言与C的差异,4,面向对象,5,类和对象的抽象关系,6,类的代码创建,7,类的成员组成及访问

1,OC语言的前世今生 , 一, 在20世纪80年代早期,布莱德.麦克(Brad Cox)设计了OC语言,它在C语言的基础上增加了一层,这意味着对C进行了扩展,从而创造出一门新的程序设计语言,支持对象的创建和操作. 二,1985年,被赶出苹果公司的乔帮主成立了Next公司; 三, 1988年,Next计算机公司获得了OC语言的授权,并发展了OC语言库和一个开发环境,1994年,Next计算机公司(同年更名为Next软件公司)和Sun公司针对NEXTSTEP系统联合发布了一个标准规范,名为OPEN

关于在事件代码中如何访问类中的变量

事件代码访问类中变量的3种方法. 在写事件代码的时候,常常需要引用主类中的变量.要访问这些变量是需要一些技巧的. 方法一: 加上final修饰符. 1 public class HelloWorld5 { 2 public static void main(String[] args) { 3 // 在变量前加上final,否则在事件代码里不能引用. 4 final String str = "孔肖寒"; 5 6 Display display = Display.getDefault

分享一个自定义的console类 让你不再纠结JS中的调试代码的兼容

分享一个自定义的console类 让你不再纠结JS中的调试代码的兼容 在写JS的过程中,为了调试我们常常会 写很多 console.log.console.info.console.group.console.warn.console.error代码来查看JS 的运行情况,但发布时又因为IE不支持console,又要去掉这些代码,一不小心就会出错 问题的产生 在写JS的过程中,为了调试我们常常会写很多 console.log.console.info.console.group.console.

Swift Tips - 在 Swift 中自定义下标访问

Untitled Document.md input[type="date"].form-control,.input-group-sm>input[type="date"].input-group-addon,.input-group-sm>.input-group-btn>input[type="date"].btn,input[type="time"].input-sm,.form-horizontal

[转载]C# FTP操作工具类

本文转载自<C# Ftp操作工具类>,仅对原文格式进行了整理. 介绍了几种FTP操作的函数,供后期编程时查阅. 参考一: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Globalization; namespace FtpTest1 { public class FtpWeb { string ftpServe

我也来写:数据库访问类DBHelper

一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以很好的工作.ADO.NET已经封装很好了,我们很容易就可以实现自己的数据库访问类. 很久前,忘记在哪里看到过了,有一个朋友写了一篇[如何做一个好用的数据库访问类](有兴趣的朋友仍然可以搜索到),这篇文章确实写得很好,作者很详细的讲解了如何设计一个好的数据库访问类:所谓“好“是指:轻量.易用.通用.高