Unity Ftp相关操作
原文链接:https://www.cnblogs.com/zhenzaizai/p/7434669.html
Ftp模块:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Net; 6 using System.Security.Cryptography; 7 using System.Text; 8 using UnityEngine; 9 using UnityEngine.UI; 10 11 namespace UpLoad 12 { 13 class UpLoadFiles 14 { 15 private static string FTPCONSTR = "ftp://192.168.xxx.136/";//FTP的服务器地址,格式为ftp://192.168.1.234/。ip地址和端口换成自己的,这些建议写在配置文件中,方便修改 16 private static string FTPUSERNAME = "test";//我的FTP服务器的用户名 17 private static string FTPPASSWORD = "123456";//我的FTP服务器的密码 18 public static float uploadProgress;//上传进度 19 public static float downloadProgress;//下载进度 20 21 #region 本地文件上传到FTP服务器 22 23 /// <summary> 24 /// 文件上传到ftp 25 /// </summary> 26 /// <param name="ftpPath">ftp的文件路径</param> 27 /// <param name="localPath">本地的文件目录</param> 28 /// <param name="fileName">可重命名文件</param> 29 /// <param name="pb">进度条</param> 30 /// <returns></returns> 31 public static bool UploadFiles(string ftpPath, string localPath, string fileName) 32 { 33 //path = "ftp://" + UserUtil.serverip + path; 34 string erroinfo = ""; 35 float percent = 0; 36 FileInfo f = new FileInfo(localPath); 37 localPath = localPath.Replace("\\", "/"); 38 bool b = MakeDir(ftpPath); 39 if (b == false) 40 { 41 return false; 42 } 43 localPath = FTPCONSTR + ftpPath + fileName; 44 FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(localPath)); 45 reqFtp.UseBinary = true; 46 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 47 reqFtp.KeepAlive = false; 48 reqFtp.Method = WebRequestMethods.Ftp.UploadFile; 49 reqFtp.ContentLength = f.Length; 50 int buffLength = 2048; 51 byte[] buff = new byte[buffLength]; 52 int contentLen; 53 FileStream fs = f.OpenRead(); 54 int allbye = (int)f.Length; 55 56 57 int startbye = 0; 58 try 59 { 60 Stream strm = reqFtp.GetRequestStream(); 61 contentLen = fs.Read(buff, 0, buffLength); 62 while (contentLen != 0) 63 { 64 strm.Write(buff, 0, contentLen); 65 startbye = contentLen + startbye; 66 percent = (float)startbye / (float)allbye * 100; 67 if (percent <= 100) 68 { 69 //Debug.Log(percent); 70 uploadProgress = percent; 71 } 72 73 contentLen = fs.Read(buff, 0, buffLength); 74 75 } 76 strm.Close(); 77 fs.Close(); 78 erroinfo = "完成"; 79 return true; 80 } 81 catch (Exception ex) 82 { 83 erroinfo = string.Format("因{0},无法完成上传", ex.Message); 84 return false; 85 } 86 } 87 88 89 90 #endregion 91 92 #region 从ftp服务器下载文件 93 94 /// <summary> 95 /// 从ftp服务器下载文件的功能----带进度条 96 /// </summary> 97 /// <param name="ftpfilepath">ftp下载的地址</param> 98 /// <param name="filePath">保存本地的地址</param> 99 /// <param name="fileName">保存的名字</param> 100 /// <param name="pb">进度条引用</param> 101 /// <returns></returns> 102 public static bool Download(string ftpfilepath, string filePath, string fileName) 103 { 104 FtpWebRequest reqFtp = null; 105 FtpWebResponse response = null; 106 Stream ftpStream = null; 107 FileStream outputStream = null; 108 try 109 { 110 filePath = filePath.Replace("我的电脑\\", ""); 111 String onlyFileName = Path.GetFileName(fileName); 112 string newFileName = filePath + onlyFileName; 113 if (File.Exists(newFileName)) 114 { 115 try 116 { 117 File.Delete(newFileName); 118 } 119 catch { } 120 121 } 122 ftpfilepath = ftpfilepath.Replace("\\", "/"); 123 string url = FTPCONSTR + ftpfilepath; 124 reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 125 reqFtp.UseBinary = true; 126 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 127 response = (FtpWebResponse)reqFtp.GetResponse(); 128 ftpStream = response.GetResponseStream(); 129 long cl = GetFileSize(url); 130 int bufferSize = 2048; 131 int readCount; 132 byte[] buffer = new byte[bufferSize]; 133 readCount = ftpStream.Read(buffer, 0, bufferSize); 134 outputStream = new FileStream(newFileName, FileMode.Create); 135 136 float percent = 0; 137 while (readCount > 0) 138 { 139 outputStream.Write(buffer, 0, readCount); 140 readCount = ftpStream.Read(buffer, 0, bufferSize); 141 percent = (float)outputStream.Length / (float)cl * 100; 142 if (percent <= 100) 143 { 144 // Debug.Log(percent); 145 downloadProgress = percent; 146 } 147 148 } 149 return true; 150 } 151 catch (Exception ex) 152 { 153 Debug.LogError("因{0},无法下载"+ex.Message); 154 return false; 155 } 156 finally 157 { 158 if (reqFtp != null) 159 reqFtp.Abort(); 160 if (response != null) 161 response.Close(); 162 if (ftpStream != null) 163 ftpStream.Close(); 164 if (outputStream != null) 165 outputStream.Close(); 166 } 167 } 168 #endregion 169 170 #region 获得文件的大小 171 /// <summary> 172 /// 获得文件大小 173 /// </summary> 174 /// <param name="url">FTP文件的完全路径</param> 175 /// <returns></returns> 176 public static long GetFileSize(string url) 177 { 178 179 long fileSize = 0; 180 try 181 { 182 FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 183 reqFtp.UseBinary = true; 184 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 185 reqFtp.Method = WebRequestMethods.Ftp.GetFileSize; 186 FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); 187 fileSize = response.ContentLength; 188 189 response.Close(); 190 } 191 catch (Exception ex) 192 { 193 Debug.LogError(ex.Message); 194 } 195 return fileSize; 196 } 197 #endregion 198 199 #region 在ftp服务器上创建文件目录 200 201 /// <summary> 202 ///在ftp服务器上创建文件目录 203 /// </summary> 204 /// <param name="dirName">文件目录</param> 205 /// <returns></returns> 206 public static bool MakeDir(string dirName) 207 { 208 try 209 { 210 string uri=(FTPCONSTR+dirName+"/"); 211 if (DirectoryIsExist(uri)) 212 { 213 Debug.Log("已存在"); 214 return true; 215 } 216 217 string url = FTPCONSTR + dirName; 218 FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 219 reqFtp.UseBinary = true; 220 // reqFtp.KeepAlive = false; 221 reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory; 222 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 223 FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); 224 response.Close(); 225 return true; 226 } 227 catch (Exception ex) 228 { 229 Debug.LogError("因{0},无法下载"+ex.Message); 230 return false; 231 } 232 233 } 234 /// <summary> 235 /// 判断ftp上的文件目录是否存在 236 /// </summary> 237 /// <param name="path"></param> 238 /// <returns></returns> 239 public static bool DirectoryIsExist(string uri) 240 { 241 string[] value = GetFileList(uri); 242 if (value == null) 243 { 244 return false; 245 } 246 else 247 { 248 return true; 249 } 250 } 251 private static string[] GetFileList(string uri) 252 { 253 StringBuilder result = new StringBuilder(); 254 try 255 { 256 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); 257 reqFTP.UseBinary = true; 258 reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 259 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 260 261 WebResponse response = reqFTP.GetResponse(); 262 StreamReader reader = new StreamReader(response.GetResponseStream()); 263 string line = reader.ReadLine(); 264 while (line != null) 265 { 266 result.Append(line); 267 result.Append("\n"); 268 line = reader.ReadLine(); 269 } 270 reader.Close(); 271 response.Close(); 272 return result.ToString().Split('\n'); 273 } 274 catch 275 { 276 return null; 277 } 278 } 279 #endregion 280 281 #region 从ftp服务器删除文件的功能 282 /// <summary> 283 /// 从ftp服务器删除文件的功能 284 /// </summary> 285 /// <param name="fileName"></param> 286 /// <returns></returns> 287 public static bool DeleteFtpFile(string fileName) 288 { 289 try 290 { 291 string url = FTPCONSTR + fileName; 292 FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); 293 reqFtp.UseBinary = true; 294 reqFtp.KeepAlive = false; 295 reqFtp.Method = WebRequestMethods.Ftp.DeleteFile; 296 reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 297 FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse(); 298 response.Close(); 299 return true; 300 } 301 catch (Exception ex) 302 { 303 //errorinfo = string.Format("因{0},无法下载", ex.Message); 304 return false; 305 } 306 } 307 #endregion 308 309 #region 从ftp服务器上获得文件夹列表 310 /// <summary> 311 /// 从ftp服务器上获得文件夹列表 312 /// </summary> 313 /// <param name="RequedstPath">服务器下的相对路径</param> 314 /// <returns></returns> 315 public static List<string> GetFtpDirctory(string RequedstPath) 316 { 317 List<string> strs = new List<string>(); 318 try 319 { 320 string uri =FTPCONSTR+RequedstPath; //根路径+路径 321 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 322 // ftp用户名和密码 323 reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 324 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 325 WebResponse response = reqFTP.GetResponse(); 326 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名 327 328 string line = reader.ReadLine(); 329 while (line != null) 330 { 331 if (line.Contains("<DIR>")) 332 { 333 string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim(); 334 strs.Add(msg); 335 } 336 line = reader.ReadLine(); 337 } 338 reader.Close(); 339 response.Close(); 340 return strs; 341 } 342 catch (Exception ex) 343 { 344 Console.WriteLine("获取目录出错:" + ex.Message); 345 } 346 return strs; 347 } 348 #endregion 349 350 #region 从ftp服务器上获得文件列表 351 /// <summary> 352 /// 从ftp服务器上获得文件列表 353 /// </summary> 354 /// <param name="RequedstPath">服务器下的相对路径</param> 355 /// <returns></returns> 356 public static List<string> GetFtpFiles(string RequedstPath) 357 { 358 List<string> strs = new List<string>(); 359 try 360 { 361 string uri = FTPCONSTR + RequedstPath; //根路径+路径 362 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 363 // ftp用户名和密码 364 reqFTP.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD); 365 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 366 WebResponse response = reqFTP.GetResponse(); 367 StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名 368 369 string line = reader.ReadLine(); 370 while (line != null) 371 { 372 if (!line.Contains("<DIR>")) 373 { 374 string msg = line.Substring(39).Trim(); 375 strs.Add(msg); 376 } 377 line = reader.ReadLine(); 378 } 379 reader.Close(); 380 response.Close(); 381 return strs; 382 } 383 catch (Exception ex) 384 { 385 Console.WriteLine("获取文件出错:" + ex.Message); 386 } 387 return strs; 388 } 389 #endregion 390 } 391 }
测试调用:
1 using System.Collections; 2 using System.Collections.Generic; 3 using System.Threading; 4 using UnityEngine; 5 using UnityEngine.UI; 6 using UpLoad; 7 8 public class Test : MonoBehaviour { 9 10 11 void Start () { 12 13 //上传n 14 //new Thread(UpLoad).Start(); 15 16 //下载 17 new Thread(DownLoad).Start(); 18 19 //创建 20 //bool bl=UpLoadFiles.MakeDir("AaaaAb"); 21 22 //删除 23 //UpLoadFiles.DeleteFtpFile("/data/uploadFile/a.zip"); 24 25 //得到文件夹列表 26 //List<string> dirs = UpLoadFiles.GetFtpDirctory(""); 27 28 //得到文件列表 29 //List<string> files = UpLoadFiles.GetFtpFiles(""); 30 31 } 32 33 void UpLoad() 34 { 35 //路径来自 "ftp://192.168.xxx.136/data/uploadFile/a.zip" 36 UpLoadFiles.UploadFiles("/data/uploadFile/", "d:/Test2/a.zip", "b.zip"); 37 38 } 39 void DownLoad() 40 { 41 UpLoadFiles.Download("/data/uploadFile/a.zip", "d:/Test2/", "C.zip"); 42 } 43 44 45 46 }