本文整理汇总了C#中Renci.SshNet.SftpClient.CreateDirectory方法的典型用法代码示例。如果您正苦于以下问题:C# SftpClient.CreateDirectory方法的具体用法?C# SftpClient.CreateDirectory怎么用?C# SftpClient.CreateDirectory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Renci.SshNet.SftpClient
的用法示例。
在下文中一共展示了SftpClient.CreateDirectory方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UploadFile
public bool UploadFile(string filePath)
{
ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
try
{
using (var sftp = new SftpClient(connectionInfo))
{
sftp.Connect();
using (var file = File.OpenRead(filePath))
{
if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
{
sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
}
sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
string filename = Path.GetFileName(filePath);
sftp.UploadFile(file, filename);
}
sftp.Disconnect();
}
}
catch (Renci.SshNet.Common.SshConnectionException)
{
Console.WriteLine("Cannot connect to the server.");
return false;
}
catch (System.Net.Sockets.SocketException)
{
Console.WriteLine("Unable to establish the socket.");
return false;
}
catch (Renci.SshNet.Common.SshAuthenticationException)
{
Console.WriteLine("Authentication of SSH session failed.");
return false;
}
return true;
}
示例2: CreateDirectoriesRecursively
private static void CreateDirectoriesRecursively(string directory, SftpClient sftp)
{
if (sftp.Exists(directory) == false)
{
// try creating one above, in case we need it:
var directoryAbove = FlatRedBall.IO.FileManager.GetDirectory(directory, FlatRedBall.IO.RelativeType.Relative);
CreateDirectoriesRecursively(directoryAbove, sftp);
sftp.CreateDirectory(directory);
}
}
示例3: CreateDirectory
private void CreateDirectory(SftpClient client, string sourceFolderName, string destination)
{
var arr = sourceFolderName.Split(DeployUtil.TransferFolder.ToCharArray());
var relativeFolder = arr.Last();
var destinationPath = Path.Combine(destination, relativeFolder);
if (!client.Exists(destinationPath))
{
client.CreateDirectory(destination);
client.ChangeDirectory(destination);
}
}
示例4: Main
//.........这里部分代码省略.........
Console.Write("-");
}
Console.Write("|");
Console.Write(c.Percentage + " % ");
Console.WriteLine();
Console.SetCursorPosition(left, top);
};
*/
string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
Console.WriteLine("connecting server ftp");
SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
client.Connect();
Console.WriteLine("server connected");
#endif
foreach (var depend in depends) {
var to = pre + shufSharp + @"\output\" + depend.Key.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
var output = "";
Application application = depend.Value;
if (application.Node) {
output += "require('./mscorlib.js');";
output += "EventEmitter= require('events.js').EventEmitter;";
} else {
//output += "require('./mscorlib.debug.js');";
}
foreach (var depe in application.IncludesAfter) {
output += string.Format("require('{0}');", depe);
}
var lines = new List<string>();
lines.Add(output);
lines.AddRange(File.ReadAllLines(to));
// lines.Add(application.After);
File.WriteAllLines(to, lines);
var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();
#if FTP
long length = new FileInfo(to).Length;
/* if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length)
{
Console.WriteLine("ftp start " + length.ToString("N0"));
webftp.Upload(loc + name, to);
Console.WriteLine("ftp complete " + to);
}
*/
if (true || !client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
Console.WriteLine("server ftp start " + length.ToString("N0"));
var fileStream = new FileInfo(to).OpenRead();
client.UploadFile(fileStream, serverloc + name, true);
fileStream.Close();
Console.WriteLine("server ftp complete " + to);
}
if (true || !client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
Console.WriteLine("server ftp start " + length.ToString("N0"));
var fileStream = new FileInfo(to).OpenRead();
client.UploadFile(fileStream, serverloc2 + name, true);
fileStream.Close();
Console.WriteLine("server ftp complete " + to);
}
#endif
if (File.Exists(@"C:\code\node\" + name) && /*new FileInfo(@"C:\code\node\" + name).Length != new FileInfo(to).Length*/ true) {
tryDelete(@"C:\code\node\" + name);
tryCopy(to, @"C:\code\node\" + name);
}
}
foreach (var d in Directory.GetDirectories(pre + shufSharp + @"\ShuffleGames\")) {
string game = d.Split('\\').Last();
var to = pre + shufSharp + @"\output\Games\" + game;
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
if (d.EndsWith("bin") || d.EndsWith("obj"))
continue;
File.WriteAllText(to + @"\app.js", File.ReadAllText(d + @"\app.js"));
#if FTP
Console.WriteLine("server ftp start ");
var fileStream = new FileInfo(to + @"\app.js").OpenRead();
if (!client.Exists(serverloc + string.Format("Games/{0}", game)))
client.CreateDirectory(serverloc + string.Format("Games/{0}", game));
client.UploadFile(fileStream, serverloc + string.Format("Games/{0}/app.js", game), true);
fileStream.Close();
Console.WriteLine("server ftp complete " + to);
#endif
}
}
示例5: SyncTo
/// <summary>
/// Sync output of current compilation to <paramref name="dir"/>
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private bool SyncTo(string dir)
{
// Copy files over
using (var sftp = new SftpClient(Machine, Port, Username, Password))
{
sftp.Connect();
if (!sftp.IsConnected)
{
return false;
}
// Perform recursive copy of all the folders under `dir`. This is required
// as the sftp client only synchronize directories at their level only, no
// subdirectory.
var dirs = new Queue<DirectoryInfo>();
dirs.Enqueue(new DirectoryInfo(dir));
var parentPath = new UDirectory(dir);
while (dirs.Count != 0)
{
var currentDir = dirs.Dequeue();
var currentPath = new UDirectory(currentDir.FullName);
foreach (var subdir in currentDir.EnumerateDirectories())
{
dirs.Enqueue(subdir);
}
// Get the destination path by adding to `Location` the relative path of `dir` to `currentDir`.
var destination = UPath.Combine(new UDirectory(Location.ItemSpec), currentPath.MakeRelative(parentPath));
Log.LogMessage("Synchronizing " + currentPath + " with " + destination.FullPath);
// Try to create a remote directory. If it throws an exception, we will assume
// for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25
try
{
sftp.CreateDirectory(destination.FullPath);
Log.LogMessage("Creating remote directory " + destination.FullPath);
}
catch (SshException)
{
// Do nothing, as this is when the directory already exists
}
// Synchronize files.
foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*"))
{
Log.LogMessage("Updating " + file.Name);
}
}
return true;
}
}
示例6: Execute
private void Execute()
{
var keyPath = textBoxFile.Text;
var host = textBoxHost.Text;
var user = textBoxUser.Text;
var pass = textBoxPass.Text;
Action _execute = () =>
{
try
{
//Read Key
Status("opening key");
FileStream file = File.OpenRead(keyPath);
//Connect to SFTP
Status("sftp connecting");
SftpClient sftp = new SftpClient(host, user, pass);
sftp.Connect();
//users home directory
string homepath = "/home/" + user + "/";
if (user == "root")
{
homepath = "/root/";
}
//Find authorized keys
string authKeys = homepath + ".ssh/authorized_keys";
if (!sftp.Exists(authKeys))
{
Status("creating");
if (!sftp.Exists(homepath + ".ssh"))
sftp.CreateDirectory(homepath + ".ssh");
sftp.Create(authKeys);
}
//Download
Status("downloading");
Stream stream = new MemoryStream();
sftp.DownloadFile(authKeys, stream);
Status("downloaded");
//Read
byte[] buffer = new byte[10240]; //No key should be this large
int length = file.Read(buffer, 0, buffer.Length);
//Validate
String strKey;
if (length < 20)
{
Status("Invalid Key (Length)");
return;
}
if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' &&
buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' &&
buffer[6] == (byte) 'a')
{
strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim();
}
else
{
Status("Invalid Key (Format)");
return;
}
stream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(stream);
//Check for key that might already exist
while (!reader.EndOfStream)
{
var line = reader.ReadLine().Trim();
if (line == strKey)
{
Status("key already exists");
return;
}
}
//Check new line
if (stream.Length != 0)
{
stream.Seek(0, SeekOrigin.End);
stream.WriteByte((byte) '\n');
}
else
{
stream.Seek(0, SeekOrigin.End);
}
//Append
Status("appending");
stream.Write(buffer, 0, length);
//Upload
Status("uploading");
stream.Seek(0, SeekOrigin.Begin);
sftp.UploadFile(stream, authKeys);
Status("done");
//.........这里部分代码省略.........
示例7: CreateRemoteDirectory
private static string CreateRemoteDirectory(SftpClient sftp, string fileName, string remoteDirectoryPath)
{
if (!string.IsNullOrWhiteSpace(remoteDirectoryPath))
{
// auto-connect
if (sftp.IsConnected == false)
sftp.Connect();
var exists = sftp.DoesRemoteFileExist(remoteDirectoryPath);
if (!exists)
sftp.CreateDirectory(remoteDirectoryPath);
return Path.Combine(remoteDirectoryPath, fileName);
}
return fileName;
}
示例8: CreatSSHDir
private static void CreatSSHDir(SftpClient ssh, string file)
{
var newDir = Tools.Misc.GetUnixDirecoryOfFile(file);
if (ssh.Exists(newDir)) return;
string[] dirs = new string[newDir.ToCharArray().Count(x => x == '/')];
dirs[0] = newDir;
for (int i = 1; i < dirs.Count(); i++)
{
dirs[i] = Tools.Misc.GetUnixDirecoryOfFile(dirs[i - 1]);
}
for (int i = dirs.Count()-1; i >= 0; i--)
{
if (ssh.Exists(dirs[i])) continue;
ssh.CreateDirectory(dirs[i]);
}
}
示例9: Sftp
private bool Sftp(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
{
bool failed = false;
error = "";
try
{
int i = 0;
filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
if (rename)
filename += ".tmp";
while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
{
filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
i++;
}
var methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) };
var con = new ConnectionInfo(server, port, username, methods.ToArray());
using (var client = new SftpClient(con))
{
client.Connect();
var filepath = filename.Trim('/').Split('/');
var path = "";
for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
{
path += filepath[iDir] + "/";
try
{
client.CreateDirectory(path);
}
catch
{
//directory exists
}
}
if (path != "")
{
client.ChangeDirectory(path);
}
filename = filepath[filepath.Length - 1];
using (Stream stream = new MemoryStream(contents))
{
client.UploadFile(stream, filename);
if (rename)
{
try
{
//delete target file?
client.DeleteFile(filename.Substring(0, filename.Length - 4));
}
catch (Exception)
{
}
client.RenameFile(filename, filename.Substring(0, filename.Length - 4));
}
}
client.Disconnect();
}
MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP");
}
catch (Exception ex)
{
error = ex.Message;
failed = true;
}
return !failed;
}
示例10: go
public void go(string filename)
{
if (string.IsNullOrWhiteSpace(filename) || connInfo == null || config.sftpEnabled == false)
{
Log.Debug("Not doing SFTP because it wasn't configured properly or at all");
return;
}
FileInfo fi = new FileInfo(filename);
if(!fi.Exists)
{
Log.Error("Can't open file for SFTPing: " + filename);
return;
}
if(!fi.DirectoryName.StartsWith(config.localBaseFolder))
{
Log.Error("Can't figure out where the file " + filename + " is relative to the base dir");
return;
}
string rel = fi.DirectoryName.Replace(config.localBaseFolder, "");
if (rel.StartsWith(Path.DirectorySeparatorChar.ToString()))
rel = rel.Substring(1);
SftpClient client = new SftpClient(connInfo);
string accum = "";
try
{
client.Connect();
string thedir = null;
foreach (string str in rel.Split(Path.DirectorySeparatorChar))
{
accum = accum + "/" + str;
thedir = config.sftpRemoteFolder + "/" + accum;
thedir = thedir.Replace("//", "/");
Log.Debug("Trying to create directory " + thedir);
try
{
client.CreateDirectory(thedir);
}
catch (SshException) { }
}
FileStream fis = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
client.BeginUploadFile(fis, thedir + "/" + fi.Name, true, (fini) =>
{
FileStream ffini = fini.AsyncState as FileStream;
if (ffini != null)
ffini.Close();
if (client != null && client.IsConnected)
{
client.Disconnect();
}
Log.Debug("Upload finished!");
if(Program.frm != null)
Program.frm.SetStatus("Upload finished! / Ready");
}, fis, (pct) =>
{
if(Program.frm != null)
{
Program.frm.SetStatus("Uploaded " + pct.ToString() + " bytes");
}
});
}
catch(Exception aiee)
{
Log.Error("Error: " + aiee.Message);
Log.Debug(aiee.StackTrace);
}
}