24Nov/094
MkDir recursively with SharpSSH SFTP
For one part of my project, i need to create automatically a path for file uploading, unfortunately, the SharpSSH will throw an excaption if you trying to create /a/b/c if /a/b does not exist. So if you need to create a code to mkdir, just use this class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | using System; using System.Collections.Generic; using System.Linq; using System.Web; using Tamir.SharpSsh; using System.Configuration; namespace DucDigital.Helper { public class SftpHelper { private static char split = '/'; public static void mkdirRecusive(string destDir, int level, bool reCheck, ref Sftp sftp) { string[] dir = cleanDirString(destDir).Split(split); if (!(level > (dir.Count() - 1))) { if (reCheck && fileExist(dir[level], getParrent(destDir, ConfigurationSettings.AppSettings["sftpPath"], level), ref sftp)) { mkdirRecusive(destDir, level + 1, true, ref sftp); } else { sftp.Mkdir(getParrent(destDir, ConfigurationSettings.AppSettings["sftpPath"], level) + dir[level]); mkdirRecusive(destDir, level + 1, false, ref sftp); } } } public static bool fileExist(string fname, string location, ref Sftp sftp) { foreach (string f in sftp.GetFileList(location)) { if (fname == f) return true; } return false; } public static string cleanDirString(string dir) { dir = dir.TrimStart(split); dir = dir.TrimEnd(split); return dir; } public static string joinDir(string dir, int level) { string[] input = cleanDirString(dir).Split(split); string output = ""; for (int i = 0; i < level; i++) { output = output + input[i] + split.ToString(); } return output; } public static string getParrent(string targetDir, string parrentConf, int level) { if (level == 0) return parrentConf; else return parrentConf + joinDir(targetDir, level); } public static string uploadPath(string path, string filename) { return ConfigurationSettings.AppSettings["sftpPath"] + path.TrimStart('/') + filename; } } } |