zoukankan      html  css  js  c++  java
  • ftp获取远程Pdf文件

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

    1、部署ftp服务器

    image

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

    2.安装adobe reader9.0阅读器

    image

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

    image

    工具箱-选择项-com组件

    image

    选择adobe PDF Reader 确定完成

    image

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

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

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

    4、开始写代码实现功能

    工程结构如下:

    image

    主窗体界面:

    image

    后端代码如下:

    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();
            }
        }
    }

    显示的阅读器窗体:

    image

    直接拖上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('
    ');
                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>

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

  • 相关阅读:
    Vue—node
    Vue—组件,父传子,子传父
    Vue—实例成员computed和watch
    Vue—条件、循环指令
    Vue初识
    BBS—登录,修改密码,退出登录
    创建ORM模型
    模板介绍
    url映射的时候指定默认参数
    自定义url转换器
  • 原文地址:https://www.cnblogs.com/dearbeans/p/7066569.html
Copyright © 2011-2022 走看看