Trying to connect to an FTP server using a port just to see if it work.
If I use port 21 I get an error: 530 Not logged in and if I use port 22 I get an error the server committed a protocol violation.
I made sure my firewall is off, is there anything else to check or my code is wrong?
try
{
FtpWebRequest directoryListRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.fakeURL.com:22/");
directoryListRequest.Method = WebRequestMethods.Ftp.ListDirectory;
directoryListRequest.Credentials = new NetworkCredential("username", "password");
using (FtpWebResponse directoryListResponse = (FtpWebResponse)directoryListRequest.GetResponse())
{
using (StreamReader directoryListResponseReader = new StreamReader(directoryListResponse.GetResponseStream()))
{
string responseString = directoryListResponseReader.ReadToEnd();
string[] results = responseString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
I was able to use Fluent FTP library to upload the file and it made my life way easier.
below an example of the code I used.
public static async Task UploadFileAsync() {
var token = new CancellationToken();
using (var ftp = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
await ftp.ConnectAsync(token);
// upload a file to an existing FTP directory
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md");
// upload a file and ensure the FTP directory is created on the server
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true);
// upload a file and ensure the FTP directory is created on the server, verify the file after upload
await ftp.UploadFileAsync(#"D:\Github\FluentFTP\README.md", "/public_html/temp/README.md", FtpRemoteExists.Overwrite, true, FtpVerify.Retry);
}
}
Related
I need the expert help. I have written the C# console base application. In which I have to upload the zip file to FTPS server. Every time I am getting the connection refuse error. But when I connect by the FileZilla its connected and working fine.
I am using FTP Protocol and Encryption type is "Required Explicit FTP over TLS" logon type normal (see the below screen shots).
The exception message as below :
"Connection failed.\r\nTLS connect: error in error\r\nCan't establish TLS connection\r\nDisconnected from server\r\nConnection failed"
Please provide any sample code or help me to correct this code.
My sample C# sample code as below :
using System;
using System.Collections.Generic;
using System.IO;
using WinSCP;
namespace FTPS
{
class Program
{
static void Main(string[] args)
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "CIR-SVN34",
UserName = "buildmachine",
Password = "Password",
FtpSecure = FtpSecure.Implicit,
PortNumber = 990
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult =
session.PutFiles(#"C:\BuildProcess\Testing.zip", #"/Apps-Panel Dev Daily Build/", false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Working only with FileZilla client
If your FileZilla configuration is working, then your server is strangely configured. It listens on implicit TLS port 990 for explicit TLS connection.
This should work:
FtpSecure = FtpSecure.Explicit,
PortNumber = 990,
Explicit TLS normally works on the standard FTP port 21.
i have a problem uploading an xlsx file to sharepoint on the deployed version. In my IIS Express in the local pc i can upload the document without any problem. When i deploy the application the server gives me an exception "No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:9000 (127.0.0.1:9000)". The Server uses a proxy server in order to execute the web request. I tried many solutions on the internet but nothing worked. I also developed a console application, which was able to upload the file without any further configuration.
This brings me to the conclusion, that the blazor server for some reason doesn't use the systems default proxy when it does the web request.
Here is my code:
public Task<bool> UploadDocument(byte[] fileBinaryArray, string fileName, string sharePointLink)
{
try
{
Debug.WriteLine("-----------------------------------" + sharePointLink);
var preparedLink = PrepareSharePointLink(sharePointLink);
Debug.WriteLine("-----------------------------------" + preparedLink);
ClientContext ctx = new PnP.Framework.AuthenticationManager().GetACSAppOnlyContext(_siteUrl, _clientId, _clientSecret);
/*ctx.ExecutingWebRequest += (sen, args) =>
{
System.Net.WebProxy myProxy = new System.Net.WebProxy("proxyIp", 8080);
args.WebRequestExecutor.WebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
args.WebRequestExecutor.WebRequest.Proxy = myProxy;
};*/
var folder = ctx.Web.GetFolderByServerRelativeUrl(preparedLink);
ctx.Load(folder);
ctx.ExecuteQuery();
folder.Files.Add(new FileCreationInformation
{
Overwrite = true,
Content = fileBinaryArray,
Url = fileName
});
ctx.ExecuteQuery();
return Task.FromResult(true);
}
catch(Exception e)
{
_eventlogService.LogError(e, _authenticationService?.UserName);
return Task.FromResult(false);
}
}
I have a C# desktop app which allows the user to backup its to google drive via the google drive api V3.
I have the following method in a class which is used to load the backups
static string[] Scopes = { DriveService.Scope.DriveFile };
static string ApplicationName = "MyApp";
private static string CreateFile(string pFilePath, string parentFolderId, DriveService service)
{
var fileMetaData = new Google.Apis.Drive.v3.Data.File();
fileMetaData.Name = Path.GetFileName(pFilePath);
fileMetaData.MimeType = "application/vnd.google-apps.file";
fileMetaData.Parents = new List<string> { parentFolderId };
FilesResource.CreateMediaUpload request;
using(var stream = new FileStream(pFilePath, FileMode.Open))
{
request = service.Files.Create(fileMetaData, stream, "application/vnd.google-apps.file");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
return file.Id;
}
Upon reaching request.Upload(), the request doesn't seem to have any issues, but later on after the file declaration, file turns out to be null, so no response body and thus no id either.
Is there something wrong with my request? I tried to see if I could catch an Exception in upload, which the method description claims would be of type IUploadProgress.Exception, but such an interface doesn't actually have an Exception property.
I've already authenticated and I managed to create a folder (which is the ID passed by argument parentFolderId, confirmed to not be null), so I am able to communicate with drive, just that this particular upload isn't working.
This is the code i use How to upload a file to Google Drive with C# .net I use the async method personally
string uploadedFileId;
// Create a new file on Google Drive
await using (var fsSource = new FileStream(UploadFileName, FileMode.Open, FileAccess.Read))
{
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
uploadedFileId = request.ResponseBody?.Id;
}
As for your code i think you need execute on the end
request.Upload().Execute;
I'm trying to upload file to FileZilla server through ftps by protocol TLS. On the server port 20 and 21 is closed. The only way how I managed to connect to server is by using FluentFTP but I couldn't upload file because of some FileZilla server bug.
https://github.com/robinrodricks/FluentFTP/issues/335
https://forum.filezilla-project.org/viewtopic.php?t=51601
public static void UploadTest(
string pathUploadFile, string addressIP, int port, string location,
string userName, string password)
{
FtpClient ftp;
Console.WriteLine("Configuring FTP to Connect to {0}", addressIP);
ftp = new FtpClient(addressIP, port, new NetworkCredential(userName, password));
ftp.ConnectTimeout = 600000;
ftp.ReadTimeout = 60000;
ftp.EncryptionMode = FtpEncryptionMode.Implicit;
ftp.SslProtocols = SslProtocols.Default | SslProtocols.Tls11 | SslProtocols.Tls12;
ftp.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
ftp.Connect();
// upload a file
ftp.UploadFile(pathUploadFile, location);
Console.WriteLine("Connected to {0}", addressIP);
ftp.Disconnect();
void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
{
// add logic to test if certificate is valid here
e.Accept = true;
}
}
Is there any way around without a violating security level? If not is there any other free library which support uploading files with TLS/SSL? I also tried this but it didn't work.
https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest.enablessl
Thanks.
You can use WinSCP .NET assembly.
It supports implicit TLS (port 990). And uses OpenSSL TLS implementation (not .NET Framework), so it should not have the problem that FluentFTP has. It definitely works for me against FileZilla FTP server, even with session resumption requirement turned on.
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "username",
Password = "password",
FtpSecure = FtpSecure.Implicit,
TlsHostCertificateFingerprint = "xx:xx:xx:...",
};
using (Session session = new Session())
{
session.Open(sessionOptions);
session.PutFiles(localPath, remotePath).Check();
}
(I'm the author of WinSCP)
For more references about the problem, see also Can connect to FTP using FileZilla or WinSCP, but not with FtpWebRequest or FluentFTP.
I am trying to use WinSCP in visual studio. I downloaded and installed WinSCP using the Managed NuGet package. I have used the below code in a web application to transfer one of the files to a remote Linux server. The code executes fine without any error, but the file is not transferred. I logged in using PuTTY to verify if the file has actually transferred, but could not locate the file. Below is the code used
public int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath)
{
int result = 0;
Session session = null;
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = HostName,
UserName = UserName,
Password = Password,
Timeout = TimeSpan.FromDays(1),
};
using (session = new Session())
{
// Connect
session.Open(sessionOptions);
// upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Ascii;
TransferOperationResult transferResult = null;
transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.GetFiles(#"\\remoteserver\folder1\folder_backups\test_files\test1.txt", #"d:\folder3\").Check();
}
result = 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
result = 1;
}
finally
{
if (session != null)
{
session.Dispose();
}
}
return result;
}
The arguments are passed as below:
project1.Upload("remote host server", "username", "password", #"\\remote host server\folder1\folder_backups\test_files\", Fileupload1.PostedFile.FileName);
The code executes without any error, but no file is uploaded nor downloaded. How to fix this?
Thanks
After the login happens in GUI - it points to /home/UserId . But the folder which i want to move the files exist in /folder1
If remote path you want to use is /folder1/, use that for remotePath argument of your Upload method, instead of obviously wrong value #"\\remote host server\folder1\folder_backups\test_files\".
project1.Upload("host", "user", "password", "/folder1/", Fileupload1.PostedFile.FileName);
Not entirely sure but looks like you've set the protocol to FTP which may not be supported by the server. If you're able to login via putty then that means SSH connection is possible. Try setting the protocol to SFTP.