ftp获取远程Pdf文件
此程序需要安装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、开始写代码实现功能
工程结构如下:
主窗体界面:
后端代码如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace myPDFDmeo
- {
- public partial class getFileForm : Form
- {
- FtpUtility ftp = new FtpUtility();
- List<string> fileNames = new List<string>();
- public getFileForm()
- {
- InitializeComponent();
- }
- //获取远程计算机文件
- private void button1_Click(object sender, EventArgs e)
- {
- //远程服务器地址
- string remoteIpAddress = ConfigurationManager.AppSettings["RemoteIpAddress"].ToString();
- //本地目录
- string localPath = ConfigurationManager.AppSettings["LocalDirectory"].ToString();
- ftp.FtpExplorer("anonymous", "chenshengwei@163.com", remoteIpAddress);
- //获取ftp当前目录下所有文件列表
- List<FileStruct> filesList = ftp.GetFileList();
- //获取本地文件夹的所有文件名
- fileNames = ftp.ProcessDirectory(localPath);
- //删除本地文件夹的所有文件
- for (int i = 0; i < fileNames.Count; i++)
- {
- string localFile = localPath + fileNames[i].ToString();
- //删除当前文件
- if (File.Exists(localFile))
- {
- File.Delete(localFile);
- }
- }
- //下载远程服务器服务器文件
- for (int i = 0; i < filesList.Count; i++)
- {
- ftp.DownloadFtp(localPath, filesList[i].Name, remoteIpAddress, "anonymous", "chenshengwei@163.comm");
- }
- //绑定文件列表到combox
- comboBox1.DataSource = filesList;
- comboBox1.DisplayMember = "Name";
- }
- //浏览
- private void button2_Click(object sender, EventArgs e)
- {
- string current = ((FileStruct)comboBox1.SelectedItem).Name;
- //将文件名称传入
- pdfViewForm p = new pdfViewForm(current);
- p.Show();
- }
- }
- }
显示的阅读器窗体:
直接拖上adobe reader组件 即可 设置窗体初始化最大化属性 设置reader组件的dock属性-fill
后端代码如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace myPDFDmeo
- {
- public partial class pdfViewForm : Form
- {
- private string parthPdfFile { get; set; }
- string localPath = ConfigurationManager.AppSettings["LocalDirectory"].ToString();
- public pdfViewForm(string currentfileName)
- {
- InitializeComponent();
- this.parthPdfFile = currentfileName;
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- axAcroPDF1.src = localPath + parthPdfFile.ToString();
- }
- }
- }
下面是ftp访问远程主机获取文件的核心实现类了
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace myPDFDmeo
- {
- enum FileListStyle
- {
- UnixStyle,
- WindowsStyle,
- Unknown
- }
- /// <summary>
- /// 文件信息
- /// </summary>
- public class FileStruct
- {
- public string Flags { get; set; }
- public bool IsDirectory { get; set; }
- public string Owner { get; set; }
- public string Group { get; set; }
- public string Size { get; set; }
- public DateTime CreateTime { get; set; }
- public string Name { get; set; }
- }
- /// <summary>
- /// Ftp访问文件目录类
- /// </summary>
- class FtpUtility
- {
- //ftp 用户名
- private string username;
- //ftp密码
- private string password;
- //ftp文件访问地址
- private string uri;
- private FileInfo fileInfo;
- /// <summary>
- /// 初始化Ftp
- /// </summary>
- /// <param name="username"></param>
- /// <param name="password"></param>
- /// <param name="uri"></param>
- public void FtpExplorer(string username, string password, string uri)
- {
- this.username = username;
- this.password = password;
- this.uri = uri;
- }
- /// <summary>
- /// 获取本地目录文件名
- /// </summary>
- /// <param name="localFile"></param>
- /// <returns></returns>
- public List<string> ProcessDirectory(string localFile)
- {
- List<string> fileNames = new List<string>();
- string[] fileEntries = Directory.GetFiles(localFile);
- for (int i = 0; i < fileEntries.Length; i++)
- {
- fileInfo = new FileInfo(fileEntries[i].ToString());
- fileNames.Add(fileInfo.Name);
- }
- return fileNames;
- }
- #region ftp下载浏览文件夹信息
- /// <summary>
- /// 得到当前目录下的所有目录和文件
- /// </summary>
- /// <param name="srcpath">浏览的目录</param>
- /// <returns></returns>
- public List<FileStruct> GetFileList( )
- {
- List<FileStruct> list = new List<FileStruct>();
- FtpWebRequest reqFtp;
- WebResponse response = null;
- string ftpuri = string.Format("ftp://{0}/", uri);
- try
- {
- reqFtp = (FtpWebRequest)FtpWebRequest.Create(ftpuri);
- reqFtp.UseBinary = true;
- reqFtp.Credentials = new NetworkCredential(username, password);
- reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
- response = reqFtp.GetResponse();
- list = ListFilesAndDirectories((FtpWebResponse)response).ToList();
- response.Close();
- }
- catch
- {
- if (response != null)
- {
- response.Close();
- }
- }
- return list;
- }
- #endregion
- #region 列出目录文件信息
- /// <summary>
- /// 列出FTP服务器上面当前目录的所有文件和目录
- /// </summary>
- public FileStruct[] ListFilesAndDirectories(FtpWebResponse Response)
- {
- StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
- string Datastring = stream.ReadToEnd();
- FileStruct[] list = GetList(Datastring);
- return list;
- }
- /// <summary>
- /// 获得文件和目录列表
- /// </summary>
- /// <param name="datastring">FTP返回的列表字符信息</param>
- private FileStruct[] GetList(string datastring)
- {
- List<FileStruct> myListArray = new List<FileStruct>();
- string[] dataRecords = datastring.Split('\n');
- FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);
- foreach (string s in dataRecords)
- {
- if (_directoryListStyle != FileListStyle.Unknown && s != "")
- {
- FileStruct f = new FileStruct();
- f.Name = "..";
- switch (_directoryListStyle)
- {
- case FileListStyle.UnixStyle:
- f = ParseFileStructFromUnixStyleRecord(s);
- break;
- case FileListStyle.WindowsStyle:
- f = ParseFileStructFromWindowsStyleRecord(s);
- break;
- }
- if (!(f.Name == "." || f.Name == ".."))
- {
- myListArray.Add(f);
- }
- }
- }
- return myListArray.ToArray();
- }
- /// <summary>
- /// 从Windows格式中返回文件信息
- /// </summary>
- /// <param name="Record">文件信息</param>
- private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)
- {
- FileStruct f = new FileStruct();
- string processstr = Record.Trim();
- string dateStr = processstr.Substring(0, 8);
- processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();
- string timeStr = processstr.Substring(0, 7);
- processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();
- DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
- myDTFI.ShortTimePattern = "t";
- f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);
- if (processstr.Substring(0, 5) == "<DIR>")
- {
- f.IsDirectory = true;
- processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
- }
- else
- {
- string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // true);
- processstr = strs[1];
- f.IsDirectory = false;
- }
- f.Name = processstr;
- return f;
- }
- /// <summary>
- /// 判断文件列表的方式Window方式还是Unix方式
- /// </summary>
- /// <param name="recordList">文件信息列表</param>
- private FileListStyle GuessFileListStyle(string[] recordList)
- {
- foreach (string s in recordList)
- {
- if (s.Length > 10
- && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))
- {
- return FileListStyle.UnixStyle;
- }
- else if (s.Length > 8
- && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))
- {
- return FileListStyle.WindowsStyle;
- }
- }
- return FileListStyle.Unknown;
- }
- /// <summary>
- /// 从Unix格式中返回文件信息
- /// </summary>
- /// <param name="Record">文件信息</param>
- private FileStruct ParseFileStructFromUnixStyleRecord(string Record)
- {
- FileStruct f = new FileStruct();
- string processstr = Record.Trim();
- f.Flags = processstr.Substring(0, 10);
- f.IsDirectory = (f.Flags[0] == 'd');
- processstr = (processstr.Substring(11)).Trim();
- _cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分
- f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
- f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
- f.Size = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);
- string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
- int m_index = processstr.IndexOf(yearOrTime);
- if (yearOrTime.IndexOf(":") >= 0) //time
- {
- processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
- }
- f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8) + " " + yearOrTime);
- f.Name = processstr; //最后就是名称
- return f;
- }
- /// <summary>
- /// 按照一定的规则进行字符串截取
- /// </summary>
- /// <param name="s">截取的字符串</param>
- /// <param name="c">查找的字符</param>
- /// <param name="startIndex">查找的位置</param>
- private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)
- {
- int pos1 = s.IndexOf(c, startIndex);
- string retString = s.Substring(0, pos1);
- s = (s.Substring(pos1)).Trim();
- return retString;
- }
- #endregion
- /// <summary>
- /// Ftp下载文档
- /// </summary>
- public int DownloadFtp(string filePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
- {
- FtpWebRequest reqFTP;
- try
- {
- FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- reqFTP.UseBinary = true;
- reqFTP.KeepAlive = false;
- reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- 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();
- return 0;
- }
- catch (Exception ex)
- {
- return -2;
- }
- }
- public string Username
- {
- get { return username; }
- set { username = value; }
- }
- public string Password
- {
- get { return password; }
- set { password = value; }
- }
- public string Uri
- {
- get { return uri; }
- set { uri = value; }
- }
- }
- }
说明:下载文件时文件名包含空格的话,会有问题,今天没时间改正了。
下面是配置文件中使用的两个简单的配置了:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
- </startup>
- <appSettings>
- <add key="RemoteIpAddress" value="127.0.0.1"/>
- <add key="LocalDirectory" value="E:\down\"/>
- </appSettings>
- </configuration>
至此,程序基本完成了,细节问题以后再改吧
ftp获取远程Pdf文件的更多相关文章
- java获取远程网络图片文件流、压缩保存到本地
1.获取远程网路的图片 /** * 根据地址获得数据的字节流 * * @param strUrl * 网络连接地址 * @return */ public static byte[] getImage ...
- SSIS 实例 从Ftp获取多个文件并对数据库进行增量更新。
整个流程 Step 1 放置一个FTP Task 将远程文件复制到本地 建立FTP链接管理器后 Is LocalPatchVariable 设置为Ture 并创建一个变量设置本地路径 Operatio ...
- Linux下实现获取远程机器文件
创建公钥秘钥实现无密码登录后即可获取到文件内容了!! A:xxx.xxx.6.xxx B:xxx.xxx.xxx.x 一.创建 A机器 ssh-keygen -t rsa 二.拷贝——将生成的公钥复制 ...
- C# 获取远程xml文件
/// <summary> /// 加载远程XML文档 /// </summary> /// <param name="URL"></pa ...
- C#——获取远程xml文件
/// <summary> /// 加载远程XML文档 /// </summary> /// <param name="URL"></pa ...
- PHP获取远程http或ftp文件的md5值
PHP获取本地文件的md5值: md5_file("/path/to/file.png"); PHP获取远程http文件的md5值: md5_file("https:// ...
- ftp服务器PDF文件在线查看
曾做过电厂的项目,有一些功能需要和甲方的厂家对接,其中就有需要实现甲方ftp服务器上的PDF.JPG等文件的查看功能.就PDF文件为例,这里使用的是pdf插件,需要将参数通过链接发给ftp,获取到PD ...
- C# 下载PDF文件(http与ftp)
1.下载http模式的pdf文件(以ASP.NET为例,将PDF存在项目的目录下,可以通过http直接打开项目下的pdf文件) #region 调用本地文件使用返回pdfbyte数组 /// < ...
- PHP学习笔记,curl,file_get_content,include和fopen四种方法获取远程文件速度测试.
这几天在做抓取.发现用PHP的file_get_contents函数来获取远程文件的过程中总是出现失败,并且效率很低下.所以就做了个测试的demo来测试下PHP中各种方法获取文件的速度. 程序里面使用 ...
随机推荐
- 洛谷 P3397 地毯 【二维差分标记】
题目背景 此题约为NOIP提高组Day2T1难度. 题目描述 在n*n的格子上有m个地毯. 给出这些地毯的信息,问每个点被多少个地毯覆盖. 输入输出格式 输入格式: 第一行,两个正整数n.m.意义如题 ...
- Gitlab运维
安装Gitlab 新建 /etc/yum.repos.d/gitlab-ce.repo [gitlab-ce] name=gitlab-ce baseurl=http://mirrors.tuna.t ...
- ( 转 ) mysql复合索引、普通索引总结
对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分.例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合 ...
- Linq 透明标识符 let
IEnumerable<Person> list = new List<Person> { , Id = }, , Id = }, , Id = }, , Id = }, , ...
- 【枚举】【权值分块】bzoj1112 [POI2008]砖块Klo
枚举长度为m的所有段,尝试用中位数更新答案. 所以需要数据结构,支持查询k大,以及大于/小于 k大值 的数的和. 平衡树.权值线段树.权值分块什么的随便呢. #include<cstdio> ...
- 【模拟】洛谷 P1328 NOIP2014提高组 day1 T1 生活大爆炸版石头剪刀布
把所有情况打表,然后随便暴力. #include<cstdio> using namespace std; int n,an,bn,p1,p2; ],b[]; ][]; int ans1, ...
- 美团在Redis上踩过的一些坑-3.redis内存占用飙升(转载)
一.现象: redis-cluster某个分片内存飙升,明显比其他分片高很多,而且持续增长.并且主从的内存使用量并不一致. 二.分析可能原因: 1. redis-cluster的bu ...
- Ionic2 常见问题及解决方案
前言 Ionic是目前较为流行的Hybird App解决方案,在Ionic开发过程中会遇到很多常见的开发问题,本文尝试对这些问题给出解决方案. 一些常识与技巧 list 有延迟,可以在ion-cont ...
- IO 流(InputStream,OutputStream)
1. InputStream,OutputStream都是抽象类,所以不能创建对象. 1个中文占两个字节 package com.ic.demo01; import java.io.File; imp ...
- 【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码
和上一份简单 上传下载一样 来,任何的方法不懂的,http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net ...