I have just installed the WinSCP library inside my VB project so I can use FTPS to transfer application files to/from a server.
However, and I apologize for my lack of knowledge, but how do I get their example code working in a practical setting?
I need to modify their code to use FTP with TLS instead of FTP over SSH as seen in their example code below.
Imports WinSCP
Friend Class Example
Public Shared Function Main() As Integer
Try
' Setup session options
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Sftp
.HostName = "example.com"
.UserName = "user"
.Password = "mypassword"
.SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
End With
Using session As New Session
' Connect
session.Open(sessionOptions)
' Download files
Dim transferOptions As New TransferOptions
transferOptions.TransferMode = TransferMode.Binary
Dim transferResult As TransferOperationResult
transferResult =
session.GetFiles("/home/user/*", "d:\download\", False, transferOptions)
' Throw on any error
transferResult.Check()
' Print results
For Each transfer In transferResult.Transfers
Console.WriteLine("Download of {0} succeeded", transfer.FileName)
Next
End Using
Return 0
Catch e As Exception
Console.WriteLine("Error: {0}", e)
Return 1
End Try
End Function
End Class
This should work:
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Ftp
.HostName = "example.com"
.UserName = "user"
.Password = "mypassword"
.FtpSecure = FtpSecure.Explicit
End With
There seem to be no YouTube videos/forum posts on a good solution for this.
So here is my solution!
This is for all the current/future programmers!
In Visual Studio, go to Tools > Extension Manager... then install NuGet Package Manager, Restart Visual Studio.
Download and install WinSCP, then download the WinSCP NuGet package from HERE.
In Visual Studio right click on your project in the Solution Explorer then click on Manage NuGet Packages... then click on Settings in the bottom left.
Add the source (folder where you downloaded the WinSCP NuGet Package) then click OK.
Next, you will see WinSCP .NET assembly show up, click on it and hit Install.
Then make sure to add Imports WinSCP to the top of your project code.
After that you can code the functions for Connecting, Uploading, and Downloading.
Use their examples provided HERE
MASSIVE TIP: Use WinSCP to connect to your FTPS server, then click on the Session tab and click on Generate session URL/code.
Inside the new window that appears, select the .NET assembly code tab. Then make sure your programming language is selected in the Language drop down.
There it is! It will show you the session connection code for your FTPS server, just copy and paste that into Visual Studio.
From there, you will have to do the rest to modify their example code, and combine it with the session connection code that WinSCP gave you.
Happy Coding!
Related
I tried to download a .bak file from the FTP and save it into a local directory in my pc.
This is my code:
Try
My.Computer.Network.DownloadFile("ftp://nameOfServer/file.bak", "C:\Users\Admin\Documents\BackUp\file.bak", "user", "password")
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
End Try
When I execute the code I get this error:
Error on the remote server: 227 Entering Passive Mode(xxx,xx,xxx,xxx,xxx,xx)
I know that I need to change it to active mode, but I canĀ“t find a way works correctly with my code.
How can I solve that? thanks
You should make sure you are downloading the files correctly by following this older edit.
After some fiddling around to recreate the issue, the issue was solved
using the following code
Dim username As String = "username"
Dim password As String = "password"
Dim address As String = "address"
Dim file As String = "file"
Dim outputFile As String = "outputFile"
My.Computer.Network.DownloadFile("ftp://" + username + ":" + password + "#" + address + "/" + file, outputFile)
Or the following was more concisely able to solve the issue
My.Computer.Network.DownloadFile("ftp://username:password#address/file", "outputLocation")
But another possible cause for your problems may have been simply caused by the output directory being missing, or more likely write protected (either by security policies or folder settings).
Finally if you have everything correct code and file-structure wise, I would advise contacting the ftp provider, and make sure the ftp server is configured and optimized properly for your use. If you cannot contact your ftp provider for help yet you can access your ftp settings, I would recommend disabling passive mode all-together for your ftp server at your own risk.
I have following network location
Dim myfolder As String = "\\10.0.0.90\myfolder\"
I am able to create a new file in this folder using following code:
File.Create (myfolder)
But when I try to read contents of this folder using code below I get error.
Code
Dim orderedFiles = New System.IO.DirectoryInfo(myfolder).GetFiles()
Error
The system detected a possible attempt to compromise security. Please
ensure that you can contact the server that authenticated you.
File writing is being done by ASP.Net page while reading is done from Windows Service. Could this be the issue?
Windows Service was running as "Local System". I right click on it, went into properties and changed the "Log on as" to some user account and now it can access network folder.
I am currently trying to open a file on my web app by retrieving the file path from a sql database
here is my code that will open the file when I double click an index in a listbox.
Protected Sub userdoubleClick()
Dim selectedPath As String
Try
fileConnection.Open()
selectedFile = FileListBox.SelectedValue
'takes the selected items from the listbox and searches the database for the file
'and will open the file for the user
fileCommand.CommandText = "SELECT filePath FROM ImportedFiles WHERE FileName = '" & selectedFile & "'"
fileDataReader = fileCommand.ExecuteReader
Do While fileDataReader.Read
selectedPath = fileDataReader.GetValue(0)
Loop
System.Diagnostics.Process.Start(selectedPath)
Catch ex As Exception
End Try
fileConnection.Close()
End Sub
When I run this on my local PC it works fine but then when I publish it to a server it wont open the file.
System.Diagnostics.Process.Start(selectedPath) will open the file on the machine running the web application; in other words, it is opening it on your local machine when running locally, but opening on the server when deployed. This just isn't going to work.
See ASP.Net Download file to client browser
If you're accessing the files from a web application, then the user identity under which the file is opened is not that of the user logged into your application. It's the user under which the IIS application pool is running. That's the user that needs to have permission granted to your shared drive.
There are many solutions to this problem, including changing the context under which the application pool is running or making the files local.
I want to open the directory of server computer using FolderBrowserDialog from the client machine.
Is it possible?
I have searched for it n haven't found the solution.
I have found others such as to browse Network Folders, here: How-to-Browse-Network-Folders-using-Folder-Dialog .
But i am looking for to browse the directory of server from the client.
here is a snippet that works fine with .net 4:
Dim dlg As New FolderBrowserDialog()
dlg.SelectedPath = "\\yourServer\share"
If dlg.ShowDialog() = DialogResult.OK Then
Dim selected = dlg.SelectedPath
' ...
End If
no need for RootFolder or any hacking - this will open the dialog on my computer (both client/server are windows-OS in a windows-domain) at the network-share and let my trill down into the folders there - at the end you will get a string like \\yourServer\share\selected\path back
My webpages are on secured server (https), and I am trying to connect the SQL Server 2008 Database, which is normal server.
I am writing connectionstring on page itself, not in web.config file. And I am getting following error:-
System.Data.SqlClient.SqlException: Login failed.
The login is from an untrusted domain and cannot be used with Windows authentication.
Please help, how can I connect it, does I have to make some webservices for it.
my code is as below:
public void FillCity()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "integrated security=SSPI;data source=dev-fcb; user id=sa;password=password;"
+"persist security info=False;database=mediapro";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from StateCityMaster where IsActive='1' order by CityName", con);
DataSet ds = new DataSet();
da.Fill(ds);
string CityName = string.Empty;
if (ds.Tables[0].Rows.Count > 0)
{
CityName = ds.Tables[0].Rows[0]["CityName"].ToString();
}
DataSet dset = new DataSet();
da.Fill(dset);
if (dset.Tables[0].Rows.Count > 0)
{
drpCity.DataSource = dset;
drpCity.DataTextField = "CityName";
drpCity.DataValueField = "CityName";
drpCity.DataBind();
}
drpCity.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
}
Your connection string is telling it to use integrated security SSPI, which will use the Windows credentials.
Set Integrated Security to false if you are going to be providing the username and password.
Also, consider putting your connection string inside of the web.config file - it is more secure and reusable.
From http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=VS.100).aspx:
When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.
If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.
I created a new Asp.Net Core MVC site and I had this same error. I was attempting to connect to my company's database while connected to the network via VPN. Here's what worked for me:
Instead of
"DevConnection": "Server=DevDBServer;Database=MyDatabase;User ID=some_userid;Password=some_password;Integrated Security=SSPI;Trusted_Connection=True;"
I used
"DevConnection": "Server=DevDBServer;Database=MyDatabase;User ID=some_userid;Password=some_password;Integrated Security=False;Trusted_Connection=False;"
The key change was to make sure that Trusted_Connection=False, which is consistent with the error message. Generally I would not use an untrusted connection. In this case I was connecting to a dev/test database so it's fine.
For future googlers:
If you do need Integrated Security and are getting this error it might be you're using a local account instead of a domain account.
I came across this running Visual Studio locally and trying to connect to a database on another machine. A workaround was to run Visual Studio as a different user, the prompt didn't work but running the command below did (make sure to replace DOMAIN\USER and you will be asked to provide credentials):
runas /netonly /user:DOMAIN\USER "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\devenv.exe"
(This is for VS2019, your path may vary).
Old question, and my symptoms are slightly different, but same error. My connection string was correct (Integrated security, and I don't provide user and pwd) with data source set to 127.0.0.1. It worked fine for years.
But recently I added a line in the static host file for testing purposes (C:\Windows\System32\drivers\etc\hosts)
127.0.0.1 www.blablatestsite.com
Removing this line and the error is gone.
I got a clue from this article (https://support.microsoft.com/en-gb/kb/896861) which talks about hostnames and loopback.
Other possible fix (if you need to keep that line in the hosts file) is to use the hostname (like MYSERVER01) instead of 127.0.0.1 in the data source of the connection string.
I had this same issue while accessing this through work where we use Azure authentication - I'd changed my password through the Azure password reset service but this only pushed through after I manually updated the password on the schema settings in my RDBMS (in my case, DataGrip).