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中各种方法获取文件的速度. 程序里面使用 ...
随机推荐
- Codeforces 651 B. Beautiful Paintings
B. Beautiful Paintings time limit per test 1 second memory limit per test 256 megabytes input stan ...
- 链式前向星写法下的DFS和BFS
Input 5 7 1 2 2 3 3 4 1 3 4 1 1 5 4 5 output 1 5 3 4 2 #include<bits/stdc++.h> using namespace ...
- POJ 1094 Sorting It All Out【拓扑排序 / 比较字母大小】
Sorting It All Out Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 38100 Accepted: 13453 ...
- ZOJ 3332 Strange Country II (竞赛图构造哈密顿通路)
链接:http://www.icpc.moe/onlinejudge/showProblem.do?problemCode=3332 本文链接:http://www.cnblogs.com/Ash-l ...
- 洛谷——P1287 盒子与球
P1287 盒子与球 题目描述 现有r个互不相同的盒子和n个互不相同的球,要将这n个球放入r个盒子中,且不允许有空盒子.问有多少种方法? 例如:有2个不同的盒子(分别编为1号和2号)和3个不同的球(分 ...
- shell head tail
head: 打印文件的前10行(默认) tail: 打印文件的后10行(默认) 如果你是个典型的开发或者部署人员,是不是觉得开始亲切起来.我们平时用的最多的命令 $tail -f cata ...
- [BZOJ2823][BZOJ1336][BZOJ1337]最小圆覆盖(随机增量法)
算法介绍网上有很多,不解释了. 给出三点坐标求圆心方法:https://blog.csdn.net/liyuanbhu/article/details/52891868 记得先random_shuff ...
- MySQL json 类型操作快速入门
MySQL 5.7.8开始支持 json类型. create table t(id int,js json,PRIMARY KEY (`id`)) 插入数据insert into t values(1 ...
- java_hibernate
入门:http://jingyan.baidu.com/article/cbf0e500965a352eab289368.html 步骤1.查看是否hibernate支持:file-->plug ...
- JavaScript数组api简单说明
1.一个数组加上另一个(一些)数组,不会修改原数组只会返回新数组 arrayObject.concat(arrayX,arrayX,......,arrayX) 2.把数组按照指定字符串分离,不会修改 ...