设为首页 收藏本站
查看: 1067|回复: 0

C#一个FTP操作封装类FTPHelper

[复制链接]

尚未签到

发表于 2015-5-26 11:37:23 | 显示全部楼层 |阅读模式
  参考了网上一些代码,作了一些调整优化。



001using System;

002using System.Collections.Generic;

003using System.Linq;

004using System.Text;

005using System.Net;

006using System.IO;

007

008public class FTPHelper

009{

010    ///

011    /// FTP请求对象

012    ///

013    FtpWebRequest request = null;

014    ///

015    /// FTP响应对象

016    ///

017    FtpWebResponse response = null;

018    ///

019    /// FTP服务器地址

020    ///

021    public string ftpURI { get; private set; }

022    ///

023    /// FTP服务器IP

024    ///

025    public string ftpServerIP { get; private set; }

026    ///

027    /// FTP服务器默认目录

028    ///

029    public string ftpRemotePath { get; private set; }

030    ///

031    /// FTP服务器登录用户名

032    ///

033    public string ftpUserID { get; private set; }

034    ///

035    /// FTP服务器登录密码

036    ///

037    public string ftpPassword { get; private set; }

038

039    ///  

040    /// 初始化

041    ///  

042    /// FTP连接地址

043    /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录

044    /// 用户名

045    /// 密码

046    public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, stringftpPassword)

047    {

048        this.ftpServerIP = ftpServerIP;

049        this.ftpRemotePath = ftpRemotePath;

050        this.ftpUserID = ftpUserID;

051        this.ftpPassword = ftpPassword;

052        this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";

053    }

054    ~FTPHelper()

055    {

056        if (response != null)

057        {

058            response.Close();

059            response = null;

060        }

061        if (request != null)

062        {

063            request.Abort();

064            request = null;

065        }

066    }

067    ///

068    /// 建立FTP链接,返回响应对象

069    ///

070    /// FTP地址

071    /// 操作命令

072    ///

073    private FtpWebResponse Open(Uri uri, string ftpMethod)

074    {

075        request = (FtpWebRequest)FtpWebRequest.Create(uri);

076        request.Method = ftpMethod;

077        request.UseBinary = true;

078        request.KeepAlive = false;

079        request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);

080        return (FtpWebResponse)request.GetResponse();

081    }

082

083    ///      

084    /// 建立FTP链接,返回请求对象      

085    ///      

086    /// FTP地址      

087    /// 操作命令      

088    private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)

089    {

090        request = (FtpWebRequest)WebRequest.Create(uri);

091        request.Method = ftpMethod;

092        request.UseBinary = true;

093        request.KeepAlive = false;

094        request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);

095        return request;

096    }

097    ///

098    /// 创建目录

099    ///

100    /// 目录名

101    public void CreateDirectory(string remoteDirectoryName)

102    {

103        response = Open(newUri(ftpURI + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory);

104    }

105    ///

106    /// 更改目录或文件名

107    ///

108    /// 当前名称

109    /// 修改后新名称

110    public void ReName(string currentName, string newName)

111    {

112        request = OpenRequest(newUri(ftpURI + currentName), WebRequestMethods.Ftp.Rename);

113        request.RenameTo = newName;

114        response = (FtpWebResponse)request.GetResponse();

115    }  

116    ///  

117    /// 切换当前目录

118    ///  

119    /// true:绝对路径 false:相对路径  

120    public void GotoDirectory(string DirectoryName, bool IsRoot)

121    {

122        if (IsRoot)

123            ftpRemotePath = DirectoryName;

124        else

125            ftpRemotePath += "/" + DirectoryName;

126

127        ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";

128    }      

129    ///

130    /// 删除目录(包括下面所有子目录和子文件)

131    ///

132    /// 要删除的带路径目录名:如web/test

133    /*

134     * 例:删除test目录

135     FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password");                 

136     helper.RemoveDirectory("web/test");

137     */

138    public void RemoveDirectory(string remoteDirectoryName)

139    {

140        GotoDirectory(remoteDirectoryName, true);

141        var listAll = ListFilesAndDirectories();

142        foreach (var m in listAll)

143        {

144            if(m.IsDirectory)         

145                RemoveDirectory(m.Path);         

146            else         

147                DeleteFile(m.Name);         

148        }

149        GotoDirectory(remoteDirectoryName, true);

150        response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);

151    }

152    ///

153    /// 文件上传

154    ///

155    /// 本地文件路径

156    public void Upload(string localFilePath)

157    {

158        FileInfo fileInf = new FileInfo(localFilePath);

159        request = OpenRequest(newUri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile);

160        request.ContentLength = fileInf.Length;

161        int buffLength = 2048;

162        byte[] buff = new byte[buffLength];

163        int contentLen;

164        using (var fs = fileInf.OpenRead())

165        {

166            using (var strm = request.GetRequestStream())

167            {

168                contentLen = fs.Read(buff, 0, buffLength);

169                while (contentLen != 0)

170                {

171                    strm.Write(buff, 0, contentLen);

172                    contentLen = fs.Read(buff, 0, buffLength);

173                }

174            }

175        }

176    }

177    ///  

178    /// 删除文件

179    ///  

180    /// 要删除的文件名

181    public void DeleteFile(string remoteFileName)

182    {

183        response = Open(newUri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile);

184    }

185

186    ///

187    /// 获取当前目录的文件和一级子目录信息

188    ///

189    ///

190    public List ListFilesAndDirectories()

191    {

192        var fileList = new List();

193        response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);

194        using (var stream = response.GetResponseStream())

195        {

196            using (var sr = new StreamReader(stream))

197            {

198                string line = null;

199                while ((line = sr.ReadLine()) != null)

200                {

201                    //line的格式如下:

202                    //08-18-13  11:05PM                 aspnet_client

203                    //09-22-13  11:39PM                 2946 Default.aspx

204                    DateTime dtDate = DateTime.ParseExact(line.Substring(0, 8), "MM-dd-yy", null);

205                    DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(8, 9));

206                    string[] arrs = line.Split(' ');

207                    var model = new FileStruct()

208                    {

209                        IsDirectory = line.IndexOf("") > 0 ? true : false,

210                        CreateTime = dtDateTime,

211                        Name = arrs[arrs.Length - 1],

212                        Path = ftpRemotePath + "/" + arrs[arrs.Length - 1]

213                    };

214                    fileList.Add(model);

215                }

216            }

217        }

218        return fileList;

219    }

220    ///      

221    /// 列出当前目录的所有文件      

222    ///      

223    public List ListFiles()

224    {

225        var listAll = ListFilesAndDirectories();

226        var listFile = listAll.Where(m => m.IsDirectory == false).ToList();

227        return listFile;

228    }

229    ///      

230    /// 列出当前目录的所有一级子目录      

231    ///      

232    public List ListDirectories()

233    {

234        var listAll = ListFilesAndDirectories();

235        var listFile = listAll.Where(m => m.IsDirectory == true).ToList();

236        return listFile;

237    }

238    ///      

239    /// 判断当前目录下指定的子目录或文件是否存在      

240    ///      

241    /// 指定的目录或文件名     

242    public bool IsExist(string remoteName)

243    {

244        var list = ListFilesAndDirectories();

245        if (list.Count(m => m.Name == remoteName) > 0)

246            return true;

247        return false;

248    }

249    ///      

250    /// 判断当前目录下指定的一级子目录是否存在      

251    ///      

252    /// 指定的目录名     

253    public bool IsDirectoryExist(string remoteDirectoryName)

254    {

255        var listDir = ListDirectories();

256        if (listDir.Count(m => m.Name == remoteDirectoryName) > 0)

257            return true;

258        return false;

259    }

260    ///      

261    /// 判断当前目录下指定的子文件是否存在     

262    ///      

263    /// 远程文件名      

264    public bool IsFileExist(string remoteFileName)

265    {

266        var listFile = ListFiles();

267        if (listFile.Count(m => m.Name == remoteFileName) > 0)

268            return true;

269        return false;

270    }

271

272    ///

273    /// 下载

274    ///

275    /// 下载后的保存路径

276    /// 要下载的文件名

277    public void Download(string saveFilePath, string downloadFileName)

278    {

279        using (FileStream outputStream = new FileStream(saveFilePath + "\\"+ downloadFileName, FileMode.Create))

280        {

281            response = Open(newUri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);

282            using (Stream ftpStream = response.GetResponseStream())

283            {

284                long cl = response.ContentLength;

285                int bufferSize = 2048;

286                int readCount;

287                byte[] buffer = new byte[bufferSize];

288                readCount = ftpStream.Read(buffer, 0, bufferSize);

289                while (readCount > 0)

290                {

291                    outputStream.Write(buffer, 0, readCount);

292                    readCount = ftpStream.Read(buffer, 0, bufferSize);

293                }

294            }

295        }

296    }

297

298   

299}

300

301public class FileStruct

302{

303    ///

304    /// 是否为目录

305    ///

306    public bool IsDirectory { get; set; }

307    ///

308    /// 创建时间

309    ///

310    public DateTime CreateTime { get; set; }

311    ///

312    /// 文件或目录名称

313    ///

314    public string Name { get; set; }

315    ///

316    /// 路径

317    ///

318    public string Path { get; set; }

319}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-70863-1-1.html 上篇帖子: FTP Send File: Source Code Review(转) 下篇帖子: FTP文件传输协议033(一些命令)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表