123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Windows.Forms;
- namespace UAS_MES_NEW.PublicMethod
- {
- class ftpOperater
- {
- //从配置文件读取FTP信息
- public static string FTPAddress = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString().Split('|')[0];
- public static string DownLoadTo = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":\" + @"打印标签\";
- private string FTPInf;
- private string ftpServerIP;
- private string ftpUser;
- private string ftpPwd;
- bool status = false;
- public ftpOperater()
- {
- //string[] FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString().Split('|');
- //this.ftpServerIP = FTPInf[0];
- //this.ftpUser = FTPInf[1];
- //this.ftpPwd = FTPInf[2];
- string FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString();
-
- //连接共享文件夹
- status = BaseUtil.connectState(FTPInf);
- }
- #region
- public void UpLoadFile(string filepath, string filename)
- {
- //上传之前判断文件是否存在
- string[] filelist = GetFileList();
- if (filelist != null)
- for (int i = 0; i < filelist.Length; i++)
- {
- if (filelist[i] == filename)
- {
- string upload = MessageBox.Show("已存在同名文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
- if (upload.ToString() != "Yes")
- {
- return;
- }
- }
- }
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
- FileInfo file = new FileInfo(filepath + "/" + filename);
- const int BufferSize = 2048;
- byte[] content = new byte[BufferSize - 1 + 1];
- int dataRead;
- using (FileStream fs = file.OpenRead())
- {
- //把上传的文件写入流
- using (Stream rs = reqFTP.GetRequestStream())
- {
- do
- {
- //每次读文件流的2KB
- dataRead = fs.Read(content, 0, BufferSize);
- rs.Write(content, 0, dataRead);
- } while (!(dataRead < BufferSize));
- rs.Close();
- }
- fs.Close();
- }
- }
- #endregion
- public void UpLoadFile(string filepath, string filename,string savepath)
- {
- if (status)
- {
- //目标路径
- string targetPath = savepath;
- //var file = Directory.GetFiles(targetPath);
- string sourceFile = Path.Combine(filepath + @"\", filename);
- string destFile = Path.Combine(targetPath + @"\", filename);
- //获取指定路径下的全部文件名
- var file = Directory.GetFiles(targetPath);
- string overwrite = "";
- for (int i = 0; i < file.Length; i++)
- {
- if (file[i].Substring(file[i].LastIndexOf(@"\") + 1) == filename)
- {
- overwrite = MessageBox.Show("已存在名为" + filename + "的文件,是否覆盖", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
- break;
- }
- }
- if (overwrite == "Yes" || overwrite == "")
- {
- //不存在文件的话进行创建
- if (!Directory.Exists(targetPath))
- Directory.CreateDirectory(targetPath);
- //将文件复制到指定位置
- File.Copy(sourceFile, destFile, true);
- }
- //string sourceFile = Path.Combine(filepath+@"\", filename);
- ////共享文件夹的目录
- //DirectoryInfo theFolder = new DirectoryInfo(savepath);
- ////获取保存文件的路径
- //string fielpath = theFolder.ToString() + @"\";
- ////执行方法
- //BaseUtil.Transport(sourceFile, fielpath, filename);
- }
- else
- {
- //ListBox1.Items.Add("未能连接!");
- MessageBox.Show("共享文件连接错误");
- }
-
- }
- /// <summary>
- /// 获取ftp服务器上的文件信息
- /// </summary>
- /// <returns>存储了所有文件信息的字符串数组</returns>
- public string[] GetFileList()
- {
- string[] downloadFiles;
- StringBuilder result = new StringBuilder();
- FtpWebRequest reqFTP;
- try
- {
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/"));
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
- WebResponse response = reqFTP.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream());
- string line = reader.ReadLine();
- while (line != null)
- {
- result.Append(line);
- result.Append("\n");
- line = reader.ReadLine();
- }
- result.Remove(result.ToString().LastIndexOf('\n'), 1);
- reader.Close();
- response.Close();
- return result.ToString().Split('\n');
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show("获取文件信息失败:" + ex.Message, "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
- downloadFiles = null;
- return downloadFiles;
- }
- }
- //获取指定的文件的内容
- public string GetFileContent(string filename)
- {
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- int bufferSize = GetFileContentLength(filename);
- byte[] buffer = new byte[bufferSize];
- ftpStream.Read(buffer, 0, bufferSize);
- ftpStream.Close();
- return Encoding.Default.GetString(buffer);
- }
- //获取指定文件的内容的字节长度
- public int GetFileContentLength(string filename)
- {
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- List<byte> buf = new List<byte>();
- while (ftpStream.ReadByte() != -1)
- {
- buf.Add((byte)ftpStream.ReadByte());
- }
- ftpStream.Close();
- return buf.ToArray().Length * 2;
- }
- /// <summary>
- /// 获取FTP上指定文件的大小
- /// </summary>
- /// <param name="filename">文件名</param>
- /// <returns>文件大小</returns>
- public long GetFileSize(string filename)
- {
- FtpWebRequest reqFTP;
- long fileSize = 0;
- try
- {
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + filename));
- reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- fileSize = response.ContentLength;
- ftpStream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show("获取文件大小时,出现异常:\n" + ex.Message, "获取文件大小失败!", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- return fileSize;
- }
- /// <summary>
- /// 实现ftp下载操作
- /// </summary>
- /// <param name="fileName">远程文件名</param>
- public string Download(string fileName)
- {
- FtpWebRequest reqFTP;
- try
- {
- FileStream outputStream = new FileStream(DownLoadTo + @"\" + fileName, FileMode.Create);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- reqFTP.UsePassive = true;
- 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 DownLoadTo + @"\" + fileName;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- return "";
- }
- }
- public string DownLoadFromSharePath(string URL,string fileName)
- {
- //目标路径
- string targetPath = FTPInf;
- //var file = Directory.GetFiles(targetPath);
- string sourceFile = Path.Combine(URL);
- string destFile = Path.Combine(DownLoadTo, fileName);
- //不存在文件的话进行创建
- if (!Directory.Exists(DownLoadTo))
- Directory.CreateDirectory(DownLoadTo);
- //将文件复制到指定位置
- try
- {
- File.Copy(sourceFile, destFile, true);
- }
- catch {
- MessageBox.Show("标签文件更新失败,不在指定维护路径"+ URL + "中或已被占用","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
- }
- return destFile;
- }
- /// <summary>
- /// 删除文件
- /// </summary>
- /// <param name="fileName"></param>
- public void Delete(string fileName)
- {
- try
- {
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + "/" + fileName));
- reqFTP.KeepAlive = false;
- reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
- reqFTP.UsePassive = true;
- string result = String.Empty;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- long size = response.ContentLength;
- Stream datastream = response.GetResponseStream();
- StreamReader sr = new StreamReader(datastream);
- result = sr.ReadToEnd();
- sr.Close();
- datastream.Close();
- response.Close();
- //Buffer.Log(string.Format("Ftp文件{1}删除成功!", DateTime.Now.ToString(), fileName));
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
|