实例介绍
【实例简介】
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Threading;
using System.Windows.Threading;
using System.Configuration;
using System.Windows.Forms;
using System.ComponentModel;
namespace FtpUpAndDownLoad
{
public class FtpUpDownLoadViewModel:BaseViewModel
{
delegate void Action();
//Ftp名
private string _ftp = System.Configuration.ConfigurationManager.AppSettings["ftp"];
public string Ftp
{
get { return _ftp; }
set
{
this._ftp = value;
NotifyPropertyChanged("Ftp");
}
}
//上传人
private string _userName = System.Configuration.ConfigurationManager.AppSettings["userName"];
public string UserName
{
get { return _userName; }
set
{
this._userName = value;
NotifyPropertyChanged("UserName");
}
}
//密码
private string _passWord = System.Configuration.ConfigurationManager.AppSettings["passWord"];
public string PassWord
{
get { return _passWord; }
set
{
this._passWord = value;
NotifyPropertyChanged("PassWord");
}
}
private List<FileStruct> _fileList = new List<FileStruct>();
public List<FileStruct> FileList
{
get { return _fileList; }
set
{
this._fileList = value;
NotifyPropertyChanged("FileList");
}
}
private string _filePath;
public string FilePath
{
get { return _filePath; }
set
{
this._filePath = value;
NotifyPropertyChanged("FilePath");
}
}
private FileStruct _selectedItem;
public FileStruct SelectedItem
{
get { return _selectedItem; }
set
{
this._selectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
private ICommand _connectCommand;
public ICommand ConnectCommand
{
get
{
return _connectCommand = new RelayCommand(OkCommand);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
private ICommand _browseCommand;
public ICommand BrowseCommand
{
get
{
return _browseCommand = new RelayCommand(Browse_Command);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
private ICommand _upLoadCommand;
public ICommand UpLoadCommand
{
get
{
return _upLoadCommand = new RelayCommand(UpLoad_Command);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
private ICommand _downLoad;
public ICommand DownLoad
{
get
{
return _downLoad = new RelayCommand(DownLoad_Command);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
//SavePath
private ICommand _savePath;
public ICommand SavePath
{
get
{
return _savePath = new RelayCommand(SavePath_Command);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
//后退 BackUp
private ICommand _backUp;
public ICommand BackUp
{
get
{
return _backUp = new RelayCommand(BackUp_Command);//或者执行使用delegate方式写方法代码,不用传方法名
}
}
private void BackUp_Command()
{
if (!string.IsNullOrWhiteSpace(LabelDir))
{
string[] Dir = LabelDir.Split('/');
string newPath = string.Empty;
for (int i = 0; i < Dir.Length - 2;i )
{
newPath = Dir[i] "/";
}
FileList.Clear();
FileList=GetFileList(newPath);
LabelDir = newPath;
}
}
private void SavePath_Command()
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
FilePath = fbd.SelectedPath; //获得选择的文件夹路径
}
/// <summary>
/// 记录上传进度开始值
/// </summary>
private int _upMinimum;
public int UpMinimum
{
get { return _upMinimum; }
set
{
this._upMinimum = value;
NotifyPropertyChanged("UpMinimum");
}
}
//Title
private string _title;
public string Title
{
get { return _title; }
set
{
this._title = value;
NotifyPropertyChanged("Title");
}
}
private double _upValue;
public double UpValue
{
get { return _upValue; }
set
{
this._upValue = value;
NotifyPropertyChanged("UpValue");
}
}
private string _progressLabel;
public string ProgressLabel
{
get { return _progressLabel; }
set
{
this._progressLabel = value;
NotifyPropertyChanged("ProgressLabel");
}
}
private string _labelDir;
public string LabelDir
{
get { return _labelDir; }
set
{
this._labelDir = value;
NotifyPropertyChanged("LabelDir");
}
}
private void DownLoad_Command() //下载
{
if (SelectedItem==null)
{
DialogResult result = MessageBox.Show("请选择一个文件", "是否选择文件", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (result == DialogResult.Yes)
{
return;
}
}
else
{
if (string.IsNullOrWhiteSpace(FilePath))
{
DialogResult result = MessageBox.Show("请选择保存位置", "是否选择保存路径", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (result == DialogResult.Yes)
{
return;
}
}
else
{
BackgroundWorker bWorker = new BackgroundWorker();
bWorker.DoWork = new DoWorkEventHandler(bWorker_DoWork);
bWorker.RunWorkerAsync();
}
}
}
void bWorker_DoWork(object sender, DoWorkEventArgs e)
{
long filesize = ReaderFile(FilePath "\\" SelectedItem.Name);
bool success = FtpBrokenDownload(LabelDir SelectedItem.Name, FilePath "\\" SelectedItem.Name, false, filesize, updateProgress);
if (success)
{
DialogResult result = MessageBox.Show("下载成功", "下载" SelectedItem.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
FilePath = string.Empty;
if (result == DialogResult.Yes)
{
this.UpValue = 0;
this.ProgressLabel = string.Empty;
return;
}
}
else
{
DialogResult result = MessageBox.Show("下载失败", "下载" SelectedItem.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
FilePath = string.Empty;
if (result == DialogResult.Yes)
{
return;
}
}
}
public static long ReaderFile(string path)
{
long _size = 0;
try
{
if (File.Exists(path))
{
FileStream _stream = new FileStream(path, FileMode.Open);
_size = _stream.Length;
_stream.Close();
_stream.Dispose();
}
}
catch (Exception ex)
{
_size = 0;
}
return _size;
}
/// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载)
/// </summary>
/// <param name="remoteFileName">远程文件名</param>
/// <param name="localFileName">保存本地的文件名(包含路径)</param>
/// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
/// <param name="size">已下载文件流大小</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns>是否下载成功</returns>
public bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action<long, long> updateProgress = null)
{
FtpWebRequest reqFTP, ftpsize;
Stream ftpStream = null;
FtpWebResponse response = null;
FileStream outputStream = null;
try
{
outputStream = new FileStream(localFileName, FileMode.Append);
if (Ftp == null || Ftp.Trim().Length == 0)
{
throw new Exception("ftp下载目标服务器地址未设置!");
}
Uri uri = new Uri(@"ftp://" Ftp remoteFileName);
ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpsize.UseBinary = true;
ftpsize.ContentOffset = size;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.ContentOffset = size;
if (ifCredential)//使用用户身份认证
{
ftpsize.Credentials = new NetworkCredential(UserName, PassWord);
reqFTP.Credentials = new NetworkCredential(UserName, PassWord);
}
ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse();
long totalBytes = re.ContentLength;
re.Close();
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
//更新进度
if (updateProgress != null)
{
updateProgress((long)totalBytes, (long)size);//更新进度条
}
long totalDownloadedByte = size;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
totalDownloadedByte = readCount totalDownloadedByte;
//outputStream.Seek(size,0);
outputStream.Write(buffer, 0, readCount);
//更新进度
if (updateProgress != null)
{
System.Windows.Application.Current.Dispatcher.Invoke(new MethodInvoker(() => {
updateProgress((long)totalBytes, (long)totalDownloadedByte);//更新进度条
}));
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception)
{
return false;
throw;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
private void UpLoad_Command() //上传
{
try
{
//FTPUploadFile(Ftp, FolderName, UserName,PassWord, filenameftp);
if (string.IsNullOrWhiteSpace(LabelDir))
{
DialogResult result = MessageBox.Show("请选择一个目录", "选择一个服务器上的目录", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
return;
}
else
{
}
}
else
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork = new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void worker_DoWork(object sender, DoWorkEventArgs args)
{
bool success = FtpUploadBroken(FilePath, LabelDir, updateProgress);
FilePath = String.Empty;
FileList.Clear();
FileList = GetFileList(LabelDir);
if (success)
{
DialogResult result = MessageBox.Show("上传成功", "上传文件", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
UpValue = 0;
ProgressLabel = string.Empty;
return;
}
}
}
private void updateProgress(long premax,long premin)
{
//UpMaximum = premax;
//UpValue = premin;
UpValue =Math.Round((Convert.ToDouble(premin * 100) / premax),0);
ProgressLabel = UpValue "%";
}
/// <summary>
/// 上传
/// </summary>
/// <param name="ftpServerIP"></param>
/// <param name="FolderName"></param>
/// <param name="ftpUserID"></param>
/// <param name="ftpPassword"></param>
/// <param name="filename"></param>
private static void FTPUploadFile(string ftpServerIP, string FolderName, string ftpUserID, string ftpPassword, string filename)
{
FileInfo uploadFile = null;
FileStream uploadFileStream = null;
FtpWebRequest ftpRequest = null;
Stream ftpStream = null;
try
{
uploadFile = new FileInfo(filename);
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" FolderName "/" uploadFile.Name));
ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftpRequest.KeepAlive = false;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.UseBinary = true;
ftpRequest.ContentLength = uploadFile.Length;
int buffLength = 2048 *1024;
byte[] buff = new byte[buffLength];
int contentLen;
//uploadFileStream = uploadFile.OpenRead();
using(uploadFileStream = File.OpenRead(uploadFile.ToString()))
ftpStream = ftpRequest.GetRequestStream();
contentLen = uploadFileStream.Read(buff, 0, buffLength);
while (contentLen != 0)
{
ftpStream.Write(buff, 0, contentLen);
contentLen = uploadFileStream.Read(buff, 0, buffLength);
}
MessageBox.Show("上传成功!");
}
catch (Exception ex)
{
MessageBox.Show("上传失败!");
}
finally
{
if (uploadFileStream != null)
{
uploadFileStream.Close();
}
if (ftpStream != null)
{
ftpStream.Close();
}
}
}
private void Browse_Command()
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.Filter = "所有文件|*.*";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.History);
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
string name = dlg.FileName;
FilePath = System.IO.Path.GetFullPath(dlg.FileName);
}
}
public FtpUpDownLoadViewModel()
{
}
//遍历文件夹中内容
public void TraverseFolder(string folder)
{
FileList.Clear();
LabelDir = folder "/";
FileList = GetFileList(LabelDir);
}
private void OkCommand() //连接
{
if (CheckFtp(Ftp, UserName, PassWord))
{
Title = string.Format("Ftp:{0} 已连接",Ftp);
FileList = GetFileList(" ");
LabelDir = "/";
}
else
{
DialogResult result=MessageBox.Show("连接失败", "是否地址正确", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
CheckFtp(Ftp, UserName, PassWord);
}
else
{
return;
}
}
}
/// <summary>
/// 验证是否连接FTP服务器
/// </summary>
/// <param name="DomainName">服务器地址</param>
/// <param name="FtpUserName">用户名</param>
/// <param name="FtpUserPwd">密码</param>
/// <returns></returns>
public bool CheckFtp(string DomainName, string FtpUserName, string FtpUserPwd)
{
bool ResultValue = true;
try
{
FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create("ftp://" DomainName);//创建FtpWebRequest对象
ftprequest.Credentials = new NetworkCredential(FtpUserName, FtpUserPwd);//设置FTP登陆信息
ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;//发送一个请求命令
FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();//响应一个请求
ftpResponse.Close();//关闭请求
}
catch
{
ResultValue = false;
}
return ResultValue;
}
/// <summary>
/// 得到当前目录下的所有目录和文件
/// </summary>
/// <param name="srcpath">浏览的目录</param>
/// <returns></returns>
public List<FileStruct> GetFileList(string srcpath)
{
List<FileStruct> list = new List<FileStruct>();
FtpWebRequest reqFtp;
WebResponse response = null;
string ftpuri = string.Format(@"ftp://{0}/{1}", Ftp, srcpath);
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;
}
/// <summary>
/// 列出FTP服务器上面当前目录的所有文件和目录
/// </summary>
public FileStruct[] ListFilesAndDirectories(FtpWebResponse Response)
{
//Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default, true);
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 filesize = "";
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).ToUniversalTime();
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);
filesize = strs[0];
processstr = processstr.Replace(filesize,"").Trim();
f.IsDirectory = false;
}
if(!string.IsNullOrWhiteSpace(filesize))
{
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (Convert.ToInt64(filesize) >= gb)
{
f.fileSize= String.Format("{0} GB", Math.Round(Convert.ToDouble(filesize) / gb,2));
}
else if (Convert.ToInt64(filesize) >= mb)
{
f.fileSize = String.Format("{0}MB", Math.Round(Convert.ToDouble(filesize) / mb,2));
}
else if (Convert.ToInt64(filesize) >= kb)
{
f.fileSize = String.Format("{0}KB", Math.Round(Convert.ToDouble(filesize) / kb,2));
}
else
f.fileSize = String.Format("{0}B", filesize);
}
f.Name = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(processstr));
return f;
}
/// <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);
_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分
string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
if (yearOrTime.IndexOf(":") >= 0) //time
{
processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
}
f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8));
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;
}
/// <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>
/// 上传文件到FTP服务器(断点续传)
/// </summary>
/// <param name="localFullPath">本地文件全路径名称:C:\Users\JianKunKing\Desktop\IronPython脚本测试工具</param>
/// <param name="remoteFilepath">远程文件所在文件夹路径</param>
/// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
/// <returns></returns>
public bool FtpUploadBroken(string localFullPath, string remoteFilepath, Action<long, long> updateProgress)
{
if (remoteFilepath == null)
{
remoteFilepath = "";
}
string newFileName = string.Empty;
bool success = true;
FileInfo fileInf = new FileInfo(localFullPath);
long allbye = (long)fileInf.Length;
newFileName = fileInf.Name;
//UpMaximum = allbye;
//if (fileInf.Name.IndexOf("#") == -1)
//{
// newFileName = RemoveSpaces(fileInf.Name);
//}
//else
//{
// newFileName = fileInf.Name.Replace("#", "#");
// newFileName = RemoveSpaces(newFileName);
//}
long startfilesize = GetFileSize(newFileName, remoteFilepath);
if (startfilesize >= allbye)
{
return false;
}
long startbye = startfilesize;
//更新进度
if (updateProgress != null)
{
updateProgress((long)allbye, (long)startfilesize);//更新进度条
}
string uri;
if (remoteFilepath.Length == 0)
{
uri = "ftp://" Ftp "/" newFileName;
}
else
{
uri = "ftp://" Ftp "/" remoteFilepath "/" newFileName;
}
FtpWebRequest reqFTP;
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(UserName,PassWord);
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;// 缓冲大小设置为2kb
byte[] buff = new byte[buffLength];
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
Stream strm = null;
try
{
// 把上传的文件写入流
strm = reqFTP.GetRequestStream();
// 每次读文件流的2kb
fs.Seek(startfilesize, 0);
int contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
startbye = contentLen;
//更新进度
if (updateProgress != null)
{
System.Windows.Application.Current.Dispatcher.Invoke(new MethodInvoker(() => {
updateProgress((long)allbye, (long)startbye);//更新进度条
}));
}
//this.UpValue = 10;
//this.UpValue = (Convert.ToDouble(startbye) / allbye)*100;
}
// 关闭两个流
strm.Close();
fs.Close();
}
catch
{
success = false;
throw;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (strm != null)
{
strm.Close();
}
}
return success;
}
// <summary>
/// 去除空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string RemoveSpaces(string str)
{
string a = "";
CharEnumerator CEnumerator = str.GetEnumerator();
while (CEnumerator.MoveNext())
{
byte[] array = new byte[1];
array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
int asciicode = (short)(array[0]);
if (asciicode != 32)
{
a = CEnumerator.Current.ToString();
}
}
string sdate = System.DateTime.Now.Year.ToString() System.DateTime.Now.Month.ToString() System.DateTime.Now.Day.ToString() System.DateTime.Now.Hour.ToString()
System.DateTime.Now.Minute.ToString() System.DateTime.Now.Second.ToString() System.DateTime.Now.Millisecond.ToString();
return a.Split('.')[a.Split('.').Length - 2] "." a.Split('.')[a.Split('.').Length - 1];
}
/// <summary>
/// 获取已上传文件大小
/// </summary>
/// <param name="filename">文件名称</param>
/// <param name="path">服务器文件路径</param>
/// <returns></returns>
public long GetFileSize(string filename, string remoteFilepath)
{
long filesize = 0;
try
{
FtpWebRequest reqFTP;
FileInfo fi = new FileInfo(filename);
string uri;
if (remoteFilepath.Length == 0)
{
uri = "ftp://" Ftp "/" fi.Name;
}
else
{
uri = "ftp://" Ftp "/" remoteFilepath "/" fi.Name;
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(UserName, PassWord);//用户,密码
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
filesize = response.ContentLength;
return filesize;
}
catch
{
return 0;
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论