首页 > Linux操作系统 > Linux操作系统 > FTP的完整类<2><转>
#region 上传文件
///
/// 上传文件到FTP服务器
///
/// 本地带有完整路径的文件名
public bool UploadFile(string LocalFullPath)
{
return UploadFile(LocalFullPath, Path.GetFileName(LocalFullPath), false);
}
///
/// 上传文件到FTP服务器
///
/// 本地带有完整路径的文件
/// 是否覆盖远程服务器上面同名的文件
public bool UploadFile(string LocalFullPath, bool OverWriteRemoteFile)
{
return UploadFile(LocalFullPath, Path.GetFileName(LocalFullPath), OverWriteRemoteFile);
}
///
/// 上传文件到FTP服务器
///
/// 本地带有完整路径的文件
/// 要在FTP服务器上面保存文件名
public bool UploadFile(string LocalFullPath, string RemoteFileName)
{
return UploadFile(LocalFullPath, RemoteFileName, false);
}
///
/// 上传文件到FTP服务器
///
/// 本地带有完整路径的文件名
/// 要在FTP服务器上面保存文件名
/// 是否覆盖远程服务器上面同名的文件
public bool UploadFile(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
{
try
{
if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
{
throw new Exception("非法文件名或目录名!");
}
if (File.Exists(LocalFullPath))
{
FileStream Stream = new FileStream(LocalFullPath, FileMode.Open, FileAccess.Read);
byte[] bt = new byte[Stream.Length];
Stream.Read(bt, 0, (Int32)Stream.Length); //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
Stream.Close();
return UploadFile(bt, RemoteFileName, OverWriteRemoteFile);
}
else
{
throw new Exception("本地文件不存在!");
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 上传文件到FTP服务器
///
/// 上传的二进制数据
/// 要在FTP服务器上面保存文件名
public bool UploadFile(byte[] FileBytes, string RemoteFileName)
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名或目录名!");
}
return UploadFile(FileBytes, RemoteFileName, false);
}
///
/// 上传文件到FTP服务器
///
/// 文件二进制内容
/// 要在FTP服务器上面保存文件名
/// 是否覆盖远程服务器上面同名的文件
public bool UploadFile(byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名!");
}
if (!OverWriteRemoteFile && FileExist(RemoteFileName))
{
throw new Exception("FTP服务上面已经存在同名文件!");
}
Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.UploadFile);
Stream requestStream = Request.GetRequestStream();
MemoryStream mem = new MemoryStream(FileBytes);
byte[] buffer = new byte[1024];
int bytesRead = 0;
int TotalRead = 0;
while (true)
{
bytesRead = mem.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
TotalRead += bytesRead;
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Close();
Response = (FtpWebResponse)Request.GetResponse();
mem.Close();
mem.Dispose();
FileBytes = null;
return true;
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
#endregion
#region 异步上传文件
///
/// 异步上传文件到FTP服务器
///
/// 本地带有完整路径的文件名
public void UploadFileAsync(string LocalFullPath)
{
UploadFileAsync(LocalFullPath, Path.GetFileName(LocalFullPath), false);
}
///
/// 异步上传文件到FTP服务器
///
/// 本地带有完整路径的文件
/// 是否覆盖远程服务器上面同名的文件
public void UploadFileAsync(string LocalFullPath, bool OverWriteRemoteFile)
{
UploadFileAsync(LocalFullPath, Path.GetFileName(LocalFullPath), OverWriteRemoteFile);
}
///
/// 异步上传文件到FTP服务器
///
/// 本地带有完整路径的文件
/// 要在FTP服务器上面保存文件名
public void UploadFileAsync(string LocalFullPath, string RemoteFileName)
{
UploadFileAsync(LocalFullPath, RemoteFileName, false);
}
///
/// 异步上传文件到FTP服务器
///
/// 本地带有完整路径的文件名
/// 要在FTP服务器上面保存文件名
/// 是否覆盖远程服务器上面同名的文件
public void UploadFileAsync(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
{
try
{
if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
{
throw new Exception("非法文件名或目录名!");
}
if (!OverWriteRemoteFile && FileExist(RemoteFileName))
{
throw new Exception("FTP服务上面已经存在同名文件!");
}
if (File.Exists(LocalFullPath))
{
MyWebClient client = new MyWebClient();
client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
client.Credentials = new NetworkCredential(this.UserName, this.Password);
if (this.Proxy != null)
{
client.Proxy = this.Proxy;
}
client.UploadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
}
else
{
throw new Exception("本地文件不存在!");
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 异步上传文件到FTP服务器
///
/// 上传的二进制数据
/// 要在FTP服务器上面保存文件名
public void UploadFileAsync(byte[] FileBytes, string RemoteFileName)
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名或目录名!");
}
UploadFileAsync(FileBytes, RemoteFileName, false);
}
///
/// 异步上传文件到FTP服务器
///
/// 文件二进制内容
/// 要在FTP服务器上面保存文件名
/// 是否覆盖远程服务器上面同名的文件
public void UploadFileAsync(byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名!");
}
if (!OverWriteRemoteFile && FileExist(RemoteFileName))
{
throw new Exception("FTP服务上面已经存在同名文件!");
}
string TempPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Templates);
if (!TempPath.EndsWith("\\"))
{
TempPath += "\\";
}
string TempFile = TempPath + Path.GetRandomFileName();
TempFile = Path.ChangeExtension(TempFile, Path.GetExtension(RemoteFileName));
FileStream Stream = new FileStream(TempFile, FileMode.CreateNew, FileAccess.Write);
Stream.Write(FileBytes, 0, FileBytes.Length); //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
Stream.Flush();
Stream.Close();
Stream.Dispose();
_isDeleteTempFile = true;
_UploadTempFile = TempFile;
FileBytes = null;
UploadFileAsync(TempFile, RemoteFileName, OverWriteRemoteFile);
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 异步上传文件完成之后触发的事件
///
/// 下载对象
/// 数据信息对象
void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
if (_isDeleteTempFile)
{
if (File.Exists(_UploadTempFile))
{
File.SetAttributes(_UploadTempFile, FileAttributes.Normal);
File.Delete(_UploadTempFile);
}
_isDeleteTempFile = false;
}
if (UploadFileCompleted != null)
{
UploadFileCompleted(sender, e);
}
}
///
/// 异步上传进度发生改变触发的事件
///
/// 下载对象
/// 进度信息对象
void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
if (UploadProgressChanged != null)
{
UploadProgressChanged(sender, e);
}
}
#endregion
#region 列出目录文件信息
///
/// 列出FTP服务器上面当前目录的所有文件和目录
///
public FileStruct[] ListFilesAndDirectories()
{
Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
string Datastring = stream.ReadToEnd();
FileStruct[] list = GetList(Datastring);
return list;
}
///
/// 列出FTP服务器上面当前目录的所有文件
///
public FileStruct[] ListFiles()
{
FileStruct[] listAll = ListFilesAndDirectories();
List
foreach (FileStruct file in listAll)
{
if (!file.IsDirectory)
{
listFile.Add(file);
}
}
return listFile.ToArray();
}
///
/// 列出FTP服务器上面当前目录的所有的目录
///
public FileStruct[] ListDirectories()
{
FileStruct[] listAll = ListFilesAndDirectories();
List
foreach (FileStruct file in listAll)
{
if (file.IsDirectory)
{
listDirectory.Add(file);
}
}
return listDirectory.ToArray();
}
///
/// 获得文件和目录列表
///
/// FTP返回的列表字符信息
private FileStruct[] GetList(string datastring)
{
List
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();
}
///
/// 从Windows格式中返回文件信息
///
/// 文件信息
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) == "
///
/// 判断文件列表的方式Window方式还是Unix方式
///
/// 文件信息列表
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;
}
///
/// 从Unix格式中返回文件信息
///
/// 文件信息
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;
}
///
/// 按照一定的规则进行字符串截取
///
/// 截取的字符串
/// 查找的字符
/// 查找的位置
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
#region 目录或文件存在的判断
///
/// 判断当前目录下指定的子目录是否存在
///
/// 指定的目录名
public bool DirectoryExist(string RemoteDirectoryName)
{
try
{
if (!IsValidPathChars(RemoteDirectoryName))
{
throw new Exception("目录名非法!");
}
FileStruct[] listDir = ListDirectories();
foreach (FileStruct dir in listDir)
{
if (dir.Name == RemoteDirectoryName)
{
return true;
}
}
return false;
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
///
/// 判断一个远程文件是否存在服务器当前目录下面
///
/// 远程文件名
public bool FileExist(string RemoteFileName)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("文件名非法!");
}
FileStruct[] listFile = ListFiles();
foreach (FileStruct file in listFile)
{
if (file.Name == RemoteFileName)
{
return true;
}
}
return false;
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
#endregion
#region 删除文件
///
/// 从FTP服务器上面删除一个文件
///
/// 远程文件名
public void DeleteFile(string RemoteFileName)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("文件名非法!");
}
Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DeleteFile);
}
catch (Exception ep)
{
ErrorMsg = ep.ToString();
throw ep;
}
}
#endregion
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22392018/viewspace-712399/ ,如需转载,请注明出处,否则将追究法律责任。