此程序需要安装ftp服务器,安装adobe reader(我这里使用的adobe reader9.0)

1、部署ftp服务器

将ftp的权限设置为允许匿名访问,部署完成

2.安装adobe reader9.0阅读器

3、设置visual studio 加载adobe reader的插件

工具箱-选择项-com组件

选择adobe PDF Reader 确定完成

到此可以在winform中使用阅读器了

文档加载如下代码可完成文档的加载显示:还是相当简单的。

axAcroPDF1.src =”c:\wyDocument.pdf”;

4、开始写代码实现功能

工程结构如下:

主窗体界面:

后端代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13.  
  14. namespace myPDFDmeo
  15. {
  16. public partial class getFileForm : Form
  17. {
  18.  
  19. FtpUtility ftp = new FtpUtility();
  20. List<string> fileNames = new List<string>();
  21. public getFileForm()
  22. {
  23. InitializeComponent();
  24. }
  25.  
  26. //获取远程计算机文件
  27. private void button1_Click(object sender, EventArgs e)
  28. {
  29. //远程服务器地址
  30. string remoteIpAddress = ConfigurationManager.AppSettings["RemoteIpAddress"].ToString();
  31. //本地目录
  32. string localPath = ConfigurationManager.AppSettings["LocalDirectory"].ToString();
  33.  
  34. ftp.FtpExplorer("anonymous", "chenshengwei@163.com", remoteIpAddress);
  35.  
  36. //获取ftp当前目录下所有文件列表
  37. List<FileStruct> filesList = ftp.GetFileList();
  38.  
  39. //获取本地文件夹的所有文件名
  40. fileNames = ftp.ProcessDirectory(localPath);
  41.  
  42. //删除本地文件夹的所有文件
  43. for (int i = 0; i < fileNames.Count; i++)
  44. {
  45. string localFile = localPath + fileNames[i].ToString();
  46. //删除当前文件
  47. if (File.Exists(localFile))
  48. {
  49. File.Delete(localFile);
  50. }
  51. }
  52. //下载远程服务器服务器文件
  53. for (int i = 0; i < filesList.Count; i++)
  54. {
  55. ftp.DownloadFtp(localPath, filesList[i].Name, remoteIpAddress, "anonymous", "chenshengwei@163.comm");
  56. }
  57. //绑定文件列表到combox
  58. comboBox1.DataSource = filesList;
  59. comboBox1.DisplayMember = "Name";
  60. }
  61.  
  62. //浏览
  63. private void button2_Click(object sender, EventArgs e)
  64. {
  65. string current = ((FileStruct)comboBox1.SelectedItem).Name;
  66. //将文件名称传入
  67. pdfViewForm p = new pdfViewForm(current);
  68. p.Show();
  69. }
  70. }
  71. }

显示的阅读器窗体:

直接拖上adobe reader组件 即可 设置窗体初始化最大化属性  设置reader组件的dock属性-fill

后端代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13.  
  14. namespace myPDFDmeo
  15. {
  16. public partial class pdfViewForm : Form
  17. {
  18. private string parthPdfFile { get; set; }
  19. string localPath = ConfigurationManager.AppSettings["LocalDirectory"].ToString();
  20. public pdfViewForm(string currentfileName)
  21. {
  22. InitializeComponent();
  23. this.parthPdfFile = currentfileName;
  24. }
  25. private void Form1_Load(object sender, EventArgs e)
  26. {
  27. axAcroPDF1.src = localPath + parthPdfFile.ToString();
  28.  
  29. }
  30.  
  31. }
  32. }

下面是ftp访问远程主机获取文件的核心实现类了

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9.  
  10. namespace myPDFDmeo
  11. {
  12. enum FileListStyle
  13. {
  14. UnixStyle,
  15. WindowsStyle,
  16. Unknown
  17. }
  18. /// <summary>
  19. /// 文件信息
  20. /// </summary>
  21. public class FileStruct
  22. {
  23. public string Flags { get; set; }
  24. public bool IsDirectory { get; set; }
  25. public string Owner { get; set; }
  26. public string Group { get; set; }
  27. public string Size { get; set; }
  28. public DateTime CreateTime { get; set; }
  29. public string Name { get; set; }
  30. }
  31. /// <summary>
  32. /// Ftp访问文件目录类
  33. /// </summary>
  34. class FtpUtility
  35. {
  36. //ftp 用户名
  37. private string username;
  38. //ftp密码
  39. private string password;
  40. //ftp文件访问地址
  41. private string uri;
  42. private FileInfo fileInfo;
  43. /// <summary>
  44. /// 初始化Ftp
  45. /// </summary>
  46. /// <param name="username"></param>
  47. /// <param name="password"></param>
  48. /// <param name="uri"></param>
  49. public void FtpExplorer(string username, string password, string uri)
  50. {
  51. this.username = username;
  52. this.password = password;
  53. this.uri = uri;
  54. }
  55. /// <summary>
  56. /// 获取本地目录文件名
  57. /// </summary>
  58. /// <param name="localFile"></param>
  59. /// <returns></returns>
  60. public List<string> ProcessDirectory(string localFile)
  61. {
  62. List<string> fileNames = new List<string>();
  63. string[] fileEntries = Directory.GetFiles(localFile);
  64. for (int i = 0; i < fileEntries.Length; i++)
  65. {
  66. fileInfo = new FileInfo(fileEntries[i].ToString());
  67. fileNames.Add(fileInfo.Name);
  68. }
  69. return fileNames;
  70. }
  71.  
  72. #region ftp下载浏览文件夹信息
  73. /// <summary>
  74. /// 得到当前目录下的所有目录和文件
  75. /// </summary>
  76. /// <param name="srcpath">浏览的目录</param>
  77. /// <returns></returns>
  78. public List<FileStruct> GetFileList( )
  79. {
  80. List<FileStruct> list = new List<FileStruct>();
  81. FtpWebRequest reqFtp;
  82. WebResponse response = null;
  83. string ftpuri = string.Format("ftp://{0}/", uri);
  84. try
  85. {
  86. reqFtp = (FtpWebRequest)FtpWebRequest.Create(ftpuri);
  87. reqFtp.UseBinary = true;
  88. reqFtp.Credentials = new NetworkCredential(username, password);
  89. reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  90. response = reqFtp.GetResponse();
  91. list = ListFilesAndDirectories((FtpWebResponse)response).ToList();
  92. response.Close();
  93. }
  94. catch
  95. {
  96. if (response != null)
  97. {
  98. response.Close();
  99. }
  100. }
  101. return list;
  102. }
  103. #endregion
  104. #region 列出目录文件信息
  105. /// <summary>
  106. /// 列出FTP服务器上面当前目录的所有文件和目录
  107. /// </summary>
  108. public FileStruct[] ListFilesAndDirectories(FtpWebResponse Response)
  109. {
  110. StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
  111. string Datastring = stream.ReadToEnd();
  112. FileStruct[] list = GetList(Datastring);
  113. return list;
  114. }
  115.  
  116. /// <summary>
  117. /// 获得文件和目录列表
  118. /// </summary>
  119. /// <param name="datastring">FTP返回的列表字符信息</param>
  120. private FileStruct[] GetList(string datastring)
  121. {
  122. List<FileStruct> myListArray = new List<FileStruct>();
  123. string[] dataRecords = datastring.Split('\n');
  124. FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
  125. foreach (string s in dataRecords)
  126. {
  127. if (_directoryListStyle != FileListStyle.Unknown && s != "")
  128. {
  129. FileStruct f = new FileStruct();
  130. f.Name = "..";
  131. switch (_directoryListStyle)
  132. {
  133. case FileListStyle.UnixStyle:
  134. f = ParseFileStructFromUnixStyleRecord(s);
  135. break;
  136. case FileListStyle.WindowsStyle:
  137. f = ParseFileStructFromWindowsStyleRecord(s);
  138. break;
  139. }
  140. if (!(f.Name == "." || f.Name == ".."))
  141. {
  142. myListArray.Add(f);
  143. }
  144. }
  145. }
  146. return myListArray.ToArray();
  147. }
  148.  
  149. /// <summary>
  150. /// 从Windows格式中返回文件信息
  151. /// </summary>
  152. /// <param name="Record">文件信息</param>
  153. private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
  154. {
  155. FileStruct f = new FileStruct();
  156. string processstr = Record.Trim();
  157. string dateStr = processstr.Substring(0, 8);
  158. processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
  159. string timeStr = processstr.Substring(0, 7);
  160. processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
  161. DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
  162. myDTFI.ShortTimePattern = "t";
  163. f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
  164. if (processstr.Substring(0, 5) == "<DIR>")
  165. {
  166. f.IsDirectory = true;
  167. processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
  168. }
  169. else
  170. {
  171. string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // true);
  172. processstr = strs[1];
  173. f.IsDirectory = false;
  174. }
  175. f.Name = processstr;
  176. return f;
  177. }
  178.  
  179. /// <summary>
  180. /// 判断文件列表的方式Window方式还是Unix方式
  181. /// </summary>
  182. /// <param name="recordList">文件信息列表</param>
  183. private FileListStyle GuessFileListStyle(string[] recordList)
  184. {
  185. foreach (string s in recordList)
  186. {
  187. if (s.Length > 10
  188. && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
  189. {
  190. return FileListStyle.UnixStyle;
  191. }
  192. else if (s.Length > 8
  193. && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
  194. {
  195. return FileListStyle.WindowsStyle;
  196. }
  197. }
  198. return FileListStyle.Unknown;
  199. }
  200.  
  201. /// <summary>
  202. /// 从Unix格式中返回文件信息
  203. /// </summary>
  204. /// <param name="Record">文件信息</param>
  205. private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
  206. {
  207. FileStruct f = new FileStruct();
  208. string processstr = Record.Trim();
  209. f.Flags = processstr.Substring(0, 10);
  210. f.IsDirectory = (f.Flags[0] == 'd');
  211. processstr = (processstr.Substring(11)).Trim();
  212. _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分
  213. f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
  214. f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
  215. f.Size = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
  216. string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
  217. int m_index = processstr.IndexOf(yearOrTime);
  218. if (yearOrTime.IndexOf(":") >= 0) //time
  219. {
  220. processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
  221. }
  222. f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8) + " " + yearOrTime);
  223. f.Name = processstr; //最后就是名称
  224. return f;
  225. }
  226.  
  227. /// <summary>
  228. /// 按照一定的规则进行字符串截取
  229. /// </summary>
  230. /// <param name="s">截取的字符串</param>
  231. /// <param name="c">查找的字符</param>
  232. /// <param name="startIndex">查找的位置</param>
  233. private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
  234. {
  235. int pos1 = s.IndexOf(c, startIndex);
  236. string retString = s.Substring(0, pos1);
  237. s = (s.Substring(pos1)).Trim();
  238. return retString;
  239. }
  240. #endregion
  241.  
  242. /// <summary>
  243. /// Ftp下载文档
  244. /// </summary>
  245. public int DownloadFtp(string filePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
  246. {
  247. FtpWebRequest reqFTP;
  248. try
  249. {
  250. FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
  251. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
  252. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  253. reqFTP.UseBinary = true;
  254. reqFTP.KeepAlive = false;
  255. reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
  256. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  257. Stream ftpStream = response.GetResponseStream();
  258. long cl = response.ContentLength;
  259. int bufferSize = 2048;
  260. int readCount;
  261. byte[] buffer = new byte[bufferSize];
  262. readCount = ftpStream.Read(buffer, 0, bufferSize);
  263. while (readCount > 0)
  264. {
  265. outputStream.Write(buffer, 0, readCount);
  266. readCount = ftpStream.Read(buffer, 0, bufferSize);
  267. }
  268. ftpStream.Close();
  269. outputStream.Close();
  270. response.Close();
  271. return 0;
  272. }
  273. catch (Exception ex)
  274. {
  275. return -2;
  276.  
  277. }
  278.  
  279. }
  280.  
  281. public string Username
  282. {
  283. get { return username; }
  284. set { username = value; }
  285. }
  286. public string Password
  287. {
  288. get { return password; }
  289. set { password = value; }
  290. }
  291. public string Uri
  292. {
  293. get { return uri; }
  294. set { uri = value; }
  295. }
  296.  
  297. }
  298. }

说明:下载文件时文件名包含空格的话,会有问题,今天没时间改正了。

下面是配置文件中使用的两个简单的配置了:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <startup>
  4. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  5. </startup>
  6. <appSettings>
  7. <add key="RemoteIpAddress" value="127.0.0.1"/>
  8. <add key="LocalDirectory" value="E:\down\"/>
  9. </appSettings>
  10. </configuration>

至此,程序基本完成了,细节问题以后再改吧

ftp获取远程Pdf文件的更多相关文章

  1. java获取远程网络图片文件流、压缩保存到本地

    1.获取远程网路的图片 /** * 根据地址获得数据的字节流 * * @param strUrl * 网络连接地址 * @return */ public static byte[] getImage ...

  2. SSIS 实例 从Ftp获取多个文件并对数据库进行增量更新。

    整个流程 Step 1 放置一个FTP Task 将远程文件复制到本地 建立FTP链接管理器后 Is LocalPatchVariable 设置为Ture 并创建一个变量设置本地路径 Operatio ...

  3. Linux下实现获取远程机器文件

    创建公钥秘钥实现无密码登录后即可获取到文件内容了!! A:xxx.xxx.6.xxx B:xxx.xxx.xxx.x 一.创建 A机器 ssh-keygen -t rsa 二.拷贝——将生成的公钥复制 ...

  4. C# 获取远程xml文件

    /// <summary> /// 加载远程XML文档 /// </summary> /// <param name="URL"></pa ...

  5. C#——获取远程xml文件

    /// <summary> /// 加载远程XML文档 /// </summary> /// <param name="URL"></pa ...

  6. PHP获取远程http或ftp文件的md5值

    PHP获取本地文件的md5值: md5_file("/path/to/file.png"); PHP获取远程http文件的md5值: md5_file("https:// ...

  7. ftp服务器PDF文件在线查看

    曾做过电厂的项目,有一些功能需要和甲方的厂家对接,其中就有需要实现甲方ftp服务器上的PDF.JPG等文件的查看功能.就PDF文件为例,这里使用的是pdf插件,需要将参数通过链接发给ftp,获取到PD ...

  8. C# 下载PDF文件(http与ftp)

    1.下载http模式的pdf文件(以ASP.NET为例,将PDF存在项目的目录下,可以通过http直接打开项目下的pdf文件) #region 调用本地文件使用返回pdfbyte数组 /// < ...

  9. PHP学习笔记,curl,file_get_content,include和fopen四种方法获取远程文件速度测试.

    这几天在做抓取.发现用PHP的file_get_contents函数来获取远程文件的过程中总是出现失败,并且效率很低下.所以就做了个测试的demo来测试下PHP中各种方法获取文件的速度. 程序里面使用 ...

随机推荐

  1. 洛谷 P3397 地毯 【二维差分标记】

    题目背景 此题约为NOIP提高组Day2T1难度. 题目描述 在n*n的格子上有m个地毯. 给出这些地毯的信息,问每个点被多少个地毯覆盖. 输入输出格式 输入格式: 第一行,两个正整数n.m.意义如题 ...

  2. Gitlab运维

    安装Gitlab 新建 /etc/yum.repos.d/gitlab-ce.repo [gitlab-ce] name=gitlab-ce baseurl=http://mirrors.tuna.t ...

  3. ( 转 ) mysql复合索引、普通索引总结

    对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分.例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合 ...

  4. Linq 透明标识符 let

    IEnumerable<Person> list = new List<Person> { , Id = }, , Id = }, , Id = }, , Id = }, , ...

  5. 【枚举】【权值分块】bzoj1112 [POI2008]砖块Klo

    枚举长度为m的所有段,尝试用中位数更新答案. 所以需要数据结构,支持查询k大,以及大于/小于 k大值 的数的和. 平衡树.权值线段树.权值分块什么的随便呢. #include<cstdio> ...

  6. 【模拟】洛谷 P1328 NOIP2014提高组 day1 T1 生活大爆炸版石头剪刀布

    把所有情况打表,然后随便暴力. #include<cstdio> using namespace std; int n,an,bn,p1,p2; ],b[]; ][]; int ans1, ...

  7. 美团在Redis上踩过的一些坑-3.redis内存占用飙升(转载)

     一.现象:     redis-cluster某个分片内存飙升,明显比其他分片高很多,而且持续增长.并且主从的内存使用量并不一致.   二.分析可能原因:  1.  redis-cluster的bu ...

  8. Ionic2 常见问题及解决方案

    前言 Ionic是目前较为流行的Hybird App解决方案,在Ionic开发过程中会遇到很多常见的开发问题,本文尝试对这些问题给出解决方案. 一些常识与技巧 list 有延迟,可以在ion-cont ...

  9. IO 流(InputStream,OutputStream)

    1. InputStream,OutputStream都是抽象类,所以不能创建对象. 1个中文占两个字节 package com.ic.demo01; import java.io.File; imp ...

  10. 【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码

    和上一份简单 上传下载一样 来,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net ...