时间:2023-07-31 08:54:01 | 来源:网站运营
时间:2023-07-31 08:54:01 来源:网站运营
如何搭建Ftp服务器:using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;namespace Module.HotPatching{ class FtpService { private NetworkCredential _credential; private string _rootUri; private bool _usePassive; private readonly List<string> _directories = new List<string>(); private readonly List<string> _files = new List<string>(); public FtpService(string userName, string password, string rootUri, bool usePassive) { if (string.IsNullOrEmpty(rootUri)) { throw new ArgumentException("rootUri"); } _credential = new NetworkCredential(userName, password); _rootUri = FixUrl(rootUri); _usePassive = usePassive; GetInfoRecursive(""); } #region utility static string FixUrl(string old) { return !string.IsNullOrEmpty(old) ? old.Replace("//", "/").TrimEnd('/') : ""; } static string FixRelativePath(string old) { return !string.IsNullOrEmpty(old) ? old.Replace("//", "/").TrimEnd('/').TrimStart('/') : ""; } #endregion #region API /// <summary> /// 将若干个文件传到 ftp 服务器 /// </summary> /// <param name="files">上传的文件的路径</param> /// <param name="ftpFolders">上传到ftpserver的目标文件夹的相对文件夹</param> /// <param name="ftpFolder">上传ftpserver的目标文件夹</param> public void Upload(string[] files, string[] ftpFolders,string ftpFolder) { if (files == null || ftpFolders == null) throw new ArgumentNullException("files == null || ftpFolders == null"); if (files.Length != ftpFolders.Length) throw new ArgumentException("files.Length != ftpFolders.Length"); if (files.Length <1) return; ftpFolder = FixRelativePath(ftpFolder); // 先创建好文件夹 List<string> targetFolders = new List<string>(); foreach (var folder in ftpFolders) { string fixedPath = FixRelativePath(folder); if (ftpFolder == fixedPath) { continue; } string[] words = fixedPath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < words.Length; i++) { string path = string.Empty; for (int j = 0; j <= i; j++) path = string.Format("{0}/{1}", path, words[j]); if (!targetFolders.Contains(path)) targetFolders.Add(path); } } foreach (var f in targetFolders) { CreateFolder(f); } // 上传 for (int i = 0; i < files.Length; i++) UploadFile(files[i], ftpFolders[i]); Console.WriteLine("All files are uploaded succeed!"); } public void UploadFile(string absolutePath, string relativeFolder) { string name = Path.GetFileName(absolutePath); string uri = CombineUri(relativeFolder, name); byte[] srcFileBuffer = File.ReadAllBytes(absolutePath); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile); request.ContentLength = srcFileBuffer.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(srcFileBuffer,0, srcFileBuffer.Length); _files.Add(string.Format("{0}/{1}", FixRelativePath(relativeFolder), name)); Console.WriteLine("Upload file succeed! {0} -> {1}", absolutePath, uri); } /// <summary> /// 将整个文件夹的内容传到ftp服务器,目录结构保持不变 /// </summary> /// <param name="folder"></param> /// <param name="ftpFolder"></param> /// <exception cref="ArgumentException"></exception> public void Upload(string folder, string ftpFolder) { if (string.IsNullOrEmpty(folder)) throw new ArgumentException("folder"); folder = FixUrl(folder); ftpFolder = FixRelativePath(ftpFolder); string[] files = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories); string[] folders = new string[files.Length]; for (int i = 0; i < files.Length; i++) { string fileDir = FixUrl(Path.GetDirectoryName(files[i])); string relativeFolder = FixRelativePath(fileDir.Replace(folder, "")); folders[i] = string.Format("{0}/{1}", ftpFolder, relativeFolder); } // 上传 Upload(files, folders,ftpFolder); } /// <summary> /// 上传字符串到ftp server /// </summary> /// <param name="src"></param> /// <param name="relativePath">Ftp上的目标文件相对路径</param> /// <exception cref="ArgumentException"></exception> public void UploadString(string src, string relativePath) { if (string.IsNullOrEmpty(src)) throw new ArgumentException("src"); string uri = CombineUri(relativePath); byte[] buffer = Encoding.Default.GetBytes(src); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile); request.ContentLength = buffer.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer,0, buffer.Length); _files.Add(FixRelativePath(relativePath)); } public string DownloadFile(string relativePath) { relativePath = FixRelativePath(relativePath); if (string.IsNullOrEmpty(relativePath)) return null; string fullUri = CombineUri(relativePath); FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.DownloadFile); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); string text = sr.ReadToEnd(); response.Dispose(); stream.Dispose(); sr.Dispose(); return text; } #endregion #region private private FtpWebRequest CreateRequest(string uri, string method) { FtpWebRequest request = (FtpWebRequest) WebRequest.Create(uri); request.Method = method; request.Credentials = _credential; request.UsePassive = _usePassive; request.UseBinary = true; request.KeepAlive = true; return request; } private void GetInfoRecursive(string relativePath) { string fullUri = CombineUri(relativePath); FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.ListDirectoryDetails); FtpWebResponse response = (FtpWebResponse) request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); List<string> dirs = new List<string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] words = line.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries); string name = words.Last(); if (name != "." && name != "..") { char type = line[0]; string newPath = !string.IsNullOrEmpty(relativePath) ? string.Format("{0}/{1}", relativePath, name) : name; newPath = FixRelativePath(newPath); if (type == 'd') { _directories.Add(newPath); dirs.Add(newPath); } else if (type == '-') { _files.Add(newPath); } } } response.Dispose(); stream.Dispose(); reader.Dispose(); foreach (var dir in dirs) { GetInfoRecursive(dir); } } private string CombineUri(params string[] relativePaths) { string uri = _rootUri; foreach (var p in relativePaths) { if (!string.IsNullOrEmpty(p)) uri = string.Format("{0}/{1}", uri, FixRelativePath(p)); } return uri; } private void CreateFolder(string relativePath) { relativePath = FixRelativePath(relativePath); if (string.IsNullOrEmpty(relativePath)) throw new ArgumentException("relativePath"); if (_directories.Contains(relativePath)) return; string fullUri = CombineUri(relativePath); try { FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.MakeDirectory); WebResponse response = request.GetResponse(); response.Dispose(); _directories.Add(relativePath); } catch (Exception e) { // ignored 如果目录已存在,会报异常,可以忽略 } Console.WriteLine("Create folder succeed! {0}", fullUri); } #endregion }}
关键词:服务