Reputation: 39
I'm setting up a file transfer through Renci SSH.NET library using SFTP and C#. And I'm stuck on this problem.
Whenever I upload a file in my ASP .NET Core program it sends the file, but it sends it as an empty file with the same name.
public async Task<IActionResult> UploadFiles(List<IFormFile> files)
{
string host = "----";
string username = "----";
string password = "----";
string Name = "";
var Stream = new MemoryStream();
List<MemoryStream> stream = new List<MemoryStream>();
var connectionInfo = new Renci.SshNet.ConnectionInfo(host, username, new PasswordAuthenticationMethod(username, password));
var sftp = new SftpClient(connectionInfo);
sftp.Connect();
sftp.ChangeDirectory("DIRECTORY");
try
{
//Read the FileName and convert it to Byte array.
foreach (var formFile in files)
{
var memoryStream = new MemoryStream();
await formFile.CopyToAsync(memoryStream);
Name = formFile.FileName;
using (var uplfileStream = memoryStream)
{
sftp.UploadFile(uplfileStream, Name, null);
}
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
sftp.Disconnect();
return View("Inbox");
}
I expect an output where a file is uploaded to the server, but the actual output is a file being uploaded to the server with the same name as the file I tried to upload, but the size is 0kb aka its empty.
Upvotes: 2
Views: 2762
Reputation: 202088
Your immediate problem is answered here:
Upload from ByteArray/MemoryStream using SSH.NET - File gets created with size 0KB
Though you do not need the intermediate MemoryStream
(and it's inefficient anyway).
using (var uplfileStream = formFile.OpenReadStream())
{
sftp.UploadFile(uplfileStream, Name);
}
Upvotes: 2