日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ftp获取远程Pdf文件

發布時間:2023/12/20 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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");}//綁定文件列表到comboxcomboBox1.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>

至此,程序基本完成了,細節問題以后再改吧

轉載于:https://www.cnblogs.com/dearbeans/p/7066569.html

總結

以上是生活随笔為你收集整理的ftp获取远程Pdf文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。