using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
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 UploadFolder)
{
//上传之前判断文件是否存在
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;
FtpCheckDirectoryExist(UploadFolder);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + UploadFolder + 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();
}
Thread.Sleep(1000);
File.Delete(filepath + "/" + filename);
}
private static void BeginWriteCallBack(IAsyncResult ar)
{
MemoryStream stream = ar.AsyncState as MemoryStream;
if (stream == null) return;
byte[] bytes = stream.ToArray();
stream.EndWrite(ar);
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
}
#endregion
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
private void UploadFileContent() {
}
//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("共享文件连接错误");
// }
//}
///
/// 获取ftp服务器上的文件信息
///
/// 存储了所有文件信息的字符串数组
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 buf = new List();
while (ftpStream.ReadByte() != -1)
{
buf.Add((byte)ftpStream.ReadByte());
}
ftpStream.Close();
return buf.ToArray().Length * 2;
}
///
/// 获取FTP上指定文件的大小
///
/// 文件名
/// 文件大小
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;
}
public void FtpCheckDirectoryExist(string destFilePath)
{
string fullDir = FtpParseDirectory(destFilePath);
string[] dirs = fullDir.Split('/');
string curDir = "/";
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
//如果是以/开始的路径,第一个为空
if (dir != null && dir.Length > 0)
{
try
{
curDir += dir + "/";
FtpMakeDir(curDir);
}
catch (Exception)
{ }
}
}
}
public string FtpParseDirectory(string destFilePath)
{
return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
}
//创建目录
public Boolean FtpMakeDir(string localFile)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + localFile);
req.Credentials = new NetworkCredential(ftpUser, ftpPwd);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
response.Close();
}
catch (Exception)
{
req.Abort();
return false;
}
req.Abort();
return true;
}
///
/// 实现ftp下载操作
///
/// 远程文件名
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;
}
///
/// 删除文件
///
///
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;
}
}
}
}