我希望创建一个简单的桌面应用程序,将文件从本地计算机传输到SFTP位置。
我尝试过以下操作,它将文件从我的本地计算机传输到我机器上的另一个位置..但是如何转移到使用用户名和密码的SFTP位置时很困难。
namespace SFTPTranfer
{
class Program
{
static void Main(string[] args)
{
try
{
string fileToCopy = "C:\\TransferFileTest.txt";
string newLocation = "C:\\copiedFiles\\copiedTransferFileTest.txt";
//string newLocation = "https:\\URL\folder1\folder2";
//string URLUser = "Test";
//string URLPassword = "Password";
string folderLocation = "C:\\copiedFiles";
if (System.IO.Directory.Exists(folderLocation))
{
if (System.IO.File.Exists(fileToCopy))
{
System.IO.File.Copy(fileToCopy, newLocation, true);
Console.WriteLine("File copied.");
}
else
{
Console.WriteLine("No such file.");
}
}
else
{
Console.WriteLine("No such directory.");
}
}
catch (Exception ex)
{
Console.Write("Error : " + ex.Message);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
任何帮助表示赞赏
更新
决定使用这种方法:http://blog.deltacode.be/2012/01/05/uploading-a-file-using-sftp-in-c-sharp/
工作正常。
答案 0 :(得分:2)
我可以推荐SSH.NET。这是一个简单的例子:
using(var fileStream = new FileStream(fileToCopy, FileMode.Open))
using(var client = new SftpClient(host, port, login, password))
{
client.Connect();
client.UploadFile(fileStream, "/path/on/server");
}
答案 1 :(得分:1)
您必须创建一个FtpWebRequest,如:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("url");
request.KeepAlive = false;
request.UseBinary = true;
request.Credentials = new NetworkCredential("USERNAME", "PASSWORD");
request.Method = WebRequestMethods.Ftp.UploadFile;
fileInfo = new FileInfo("FILEPATH");
request.ContentLength = fileInfo.Length;
FileStream fileStream = fileInfo.OpenRead();
Stream requestStream = request.GetRequestStream();
while (totalBytes > 0)
{
int bytes = fileStream.Read(buffer, 0, buffer.Length);
requestStream.Write(buffer, 0, bytes);
totalBytes = totalBytes - bytes;
}
fileStream.Close();
requestStream.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)request.GetResponse();
string value = uploadResponse.StatusDescription;
uploadResponse.Close();
这适用于FTP-Connection。不确定它是否适用于SFTP。但它应该工作
修改强> 你必须设置
request.EnableSsl = true;
它应该适用于SFTP