C# FTP 自动创建目录/上传文件
2015-09-21 15:09
856 查看
//上传文件 public static Boolean FtpUpload(string ftpPath,string localFile) { //检查目录是否存在,不存在创建 FtpCheckDirectoryExist(ftpPath); FileInfo fi = new FileInfo(localFile); FileStream fs = fi.OpenRead(); long length = fs.Length; FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + ftpPath + fi.Name); req.Credentials = new NetworkCredential(ftpUserID, ftpPassword); req.Method = WebRequestMethods.Ftp.UploadFile; req.ContentLength = length; req.Timeout = 10 * 1000; try { Stream stream = req.GetRequestStream(); int BufferLength = 2048; //2K byte[] b = new byte[BufferLength]; int i; while ((i = fs.Read(b, 0, BufferLength)) > 0) { stream.Write(b, 0, i); } stream.Close(); stream.Dispose(); } catch (Exception e) { ErrLog(e.Message + e.StackTrace); return false; } finally { fs.Close(); req.Abort(); } req.Abort(); return true; } //判断文件的目录是否存,不存则创建 public static void FtpCheckDirectoryExist(string destFilePath) { string fullDir = FtpParseDirectory(destFilePath); string[] dirs = fullDir.Split('/'); string curDir = "/"; for (int i = 0; i < dirs.Length; i++) { string dir = dirs[i]; //如果是以/开始的路径,第一个为空 if (dir != null && dir.Length > 0) { try { curDir += dir + "/"; FtpMakeDir(curDir); } catch (Exception) {} } } } public static string FtpParseDirectory(string destFilePath) { return destFilePath.Substring(0, destFilePath.LastIndexOf("/")); } //创建目录 public static Boolean FtpMakeDir(string localFile) { FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + localFile); req.Credentials = new NetworkCredential(ftpUserID, ftpPassword); req.Method = WebRequestMethods.Ftp.MakeDirectory; try { FtpWebResponse response = (FtpWebResponse)req.GetResponse(); response.Close(); } catch (Exception) { req.Abort(); return false; } req.Abort(); return true; }
相关文章推荐
- C#获取网页源代码的方法
- C# 生成二维码
- C#的类型转换
- C#绘图双缓冲
- c# 在 ComboBox 控件中创建大小可变的文本
- C#泛型类之List<T>
- C# 如何获取错误所在行数
- C#视频播放器
- C#利用反射给实体属性赋值
- C#中List的Find方法的使用
- C#执行异步操作的几种方式总结比较
- C#银行系统
- C# explicit与implicit
- C#中tick 与秒的对应关系
- C#如何更新服务?
- C#实现MD5加密
- C#修改AD域的用户密码时报“调用的目标发生了异常”的问题。
- 关于异常Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
- C#使用模版创建execl文件
- C#之回到了最初的起点----解决方案、项目、程序集、命名空间