Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

dwinn86

Hi,

I have managed to get the connection now going, but for some reason, it goes through the entire process of uploading the file.

But it doesnt seem to actually upload the file.

This is the code I have for uploading.

If (mySession.Opened) Then


                MsgBox("Uploading")

                transferOptions.TransferMode = TransferMode.Binary
               
                'transferResult = session.PutFiles(FileUpload1.ToString, "/", True, transferOptions)
                transferResult = mySession.PutFiles("C:\FTPDirectoryFiles\" + FileUpload1.FileName, "ftp://user:password@xx.x.xx.xx/In/", False, transferOptions)
               
                ' Throw on any error
                transferResult.Check()

            End If


If you could advise, that would be great.

Many thanks again.
dwinn86

Heya, im back again...

I have got the site going, and am trying to upload a file, but it seems that the session isnt able to open the session options?

The code is:

Protected Function ProcessFiles() As String


        Dim Path As String
        Path = "C:\Program Files\WinSCP\WinSCP.exe"

        Try
            ' Setup session options
            Dim sessionOptions As New SessionOptions
            MsgBox("Processing")
            With sessionOptions
                .Protocol = Protocol.Sftp
                .HostName = "xx.x.xx.xx"
                '.PortNumber = 22
                .UserName = "user"
                .Password = "password"
                '.SshHostKey = "ssh-rsa xxxx xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

            End With

            'Set up the session
            'Using session As Session = New Session
            Dim mySession As New Session
                ' Connect
            MsgBox("Connecting")
            mySession.ExecutablePath = Path

            mySession.Open(sessionOptions)
                'Dim transferResult As TransferOperationResult

                ' Upload files
                'Dim transferOptions As New TransferOptions
                ' Print results
                'Dim transfer As TransferEventArgs
                'For Each transfer In transferResult.Transfers
                'Console.WriteLine("Upload of {0} succeeded", transfer.FileName)
                'Console.Read()
                'Next

                MsgBox("About to upload")

            If (mySession.Opened) Then

                MsgBox("Uploading")

                'TransferOptions.TransferMode = TransferMode.Binary

                'transferResult = session.PutFiles(FileUpload1.ToString, "/", True, transferOptions)
                'transferResult = session.PutFiles(FileUpload1.ToString, "ftp://xx.x.xx.xx/In/", False, TransferOptions)

                ' Throw on any error
                'transferResult.Check()

            End If

            'End Using

            Return 0
        Catch e As Exception
            Console.WriteLine("Error: {0}", e)

            Return 1
        End Try

    End Function



I dont suppose you can help advise why this is?

Many thanks
dwinn86

To be honest with you...I am self taught at VB in Visual Studio...never been taken through best practises or anything.

That is why I have been submitting a lot of threads :-)

What exceptions are they?
lynzepiper

dwinn86

Thank you.

I will have a go at doing that when I get back in to work tomorrow.

When I do projects from now on is it best to keep that in mind?

The .aspx webform keeps your ASP and HTML code and then the code behind form (aspx.vb) keeps all of your vb code?

So your sub-routines, functions etc?

Keep your VB code sperate from your actual interface code?
lynzepiper

dwinn86

Does that mean that when I go on to the page and select the file to upload, the program will automatically look in to the code behind form and then go through all the code?

I asumed it just went through the .aspx page?
lynzepiper

dwinn86

Ok then, so to clarify, ALL of my VB code (routines etc) should all be put in to my code behind and only leave the HTML code and ASP.Net code in my webform??
lynzepiper

dwinn86

Could you please elaborate?
lynzepiper

dwinn86

This is my main .aspx page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="InDirectory.aspx.vb" Inherits="FTPUploadSite.InDirectory" %>


<%@ Import Namespace="FTPUploadSite" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web.UI.Page" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            font-family: Arial;
            font-size: xx-large;
        }
    </style>
</head>
<body style="height: 797px; width: 1621px; background-color: #CCFFFF">
    <form id="form1" runat="server">
    <div class="style1" style="text-align: center">
   
        FTP In Directory</div>
    <p>
        &nbsp;</p>
        <script runat="server">
            Protected Sub butUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles butUpload.Click
               
                'Declaring the path of where the file should be uploaded to on the FTP site.
                'Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create("ftp://xx.xx.xx.xx/In/" + FileUpload1.FileName), FtpWebRequest)
                Dim objOutlook As Object
                Dim objOutlookMsg As Object

                'If no file has been selected, give error message.
                If FileUpload1.HasFile = False Then
                    MsgBox("A file needs to be selected!")
                End If
                               
                'If a file has been selected, carry out the file upload process.
                If FileUpload1.HasFile = True Then
                    Try
                        MsgBox ("About to process")
                        ProcessFiles()
                       
                        'ftp.Credentials = New System.Net.NetworkCredential("user", "password")
                        'ftp.KeepAlive = False
                        'ftp.Timeout = 20000
                        'ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile
                        'ftp.UseBinary = True
                       
                        Const olMailItem = 0
                        'The importance level of the email.
                        Const olImportanceHigh = 1
                        'Who the email is going to.
                        Const olTo = 1

                        objOutlook = CreateObject("Outlook.Application")
                        'Creating new mail item.
                        objOutlookMsg = objOutlook.CreateItem(olMailItem)

                        'Declaring the directory to read the file from.
                        'Dim sftpFileStream As New FileStream("C:\FTPDirectoryFiles\" + FileUpload1.FileName, FileMode.Open)
                        'Getting the length of the file.
                        'Dim sftpBuffer(sftpFileStream.Length) As Byte
                         
                        MsgBox("Carrying On")
                       
                        'Reading in the file.
                        'sftpFileStream.Read(sftpBuffer, 0, sftpFileStream.Length)

                        'Upload the file
                        'Dim ftpGetStream As Stream = ftp.GetRequestStream()
                        'ftpGetStream.Write(ftpBuffer, 0, ftpFileStream.Length)

                        'Closes off connections.
                        'ftpGetStream.Close()
                        'ftpFileStream.Close()
                       
                        'Getting a response from the FTP site.
                        'Dim ftpResponse As FtpWebResponse = CType(ftp.GetResponse(), FtpWebResponse)
                       
                        'SCRIPT TO SEND EMAIL GOES HERE!
                        With objOutlookMsg
                            'The email address of the recipient.
                            Dim objOutlookRecip As Object = .Recipients.Add("dwinn@email.co.uk")
                            objOutlookRecip.type = olTo
                                 
                            'Declaring the subject of the email.
                            .Subject = "FTP File Upload Confirmation"
                            'Declaring what will be in the email.
                            .Body = "Hello, this is confirmation that the file: " + FileUpload1.FileName + " has been uploaded successfully..."
                            'The importance level of the email.
                            .Importance = olImportanceHigh
                            'Sending the email.
                            .send()
                        End With
                        objOutlookMsg = Nothing
                        objOutlook = Nothing
                       
                    Catch ex As Exception

                        MsgBox("File: " + FileUpload1.FileName + " has been uploaded...")
                       
                    End Try
                End If
            End Sub

            Protected Sub butDirectories_Click(ByVal sender As Object, ByVal e As EventArgs) Handles butDirectories.Click
               
                'Takes the user to the FTP Directories screen.
                Response.Redirect("FTPDirectories.aspx")
               
            End Sub

            Protected Sub butSystemLogOut(ByVal sender As Object, ByVal e As EventArgs) Handles butSysLogOut.Click
               
                'Takes the user to the User Login screen.
                Response.Redirect("UserLogin.aspx")
               
            End Sub
           
        </script>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p style="text-align: center">
        <asp:FileUpload ID="FileUpload1" runat="server" />
&nbsp;
        </p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        <asp:Button ID="butUpload" runat="server" Text="Upload File" />
    &nbsp;
    &nbsp;<asp:Button ID="Button4" runat="server"
            PostBackUrl="ftp://xx.x.xx.xx/dwinn/In/" style="margin-left: 1px"
            Text="FTP List" />
    &nbsp;&nbsp;
        <asp:Button ID="butDirectories" runat="server" Text="Back to FTP Directories"
            Width="176px" />
&nbsp;&nbsp;
        <asp:Button ID="butSysLogOut" runat="server" Text="Exit the system"
            Width="176px" />
    </p>
    <p style="text-align: center">
        &nbsp;
    </p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
&nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    </form>
</body>
</html>


This is my code behind page:

Imports System.Net

Imports System.IO
Imports WinSCP

Public Class InDirectory
    Inherits System.Web.UI.Page

    Protected Function ProcessFiles() As String

        Dim Path As String
        Path = "C:\Program Files\WinSCP\WinSCP.exe"

        Try
            ' Setup session options
            Dim sessionOptions As New SessionOptions
            MsgBox("Processing")
            With sessionOptions
                .HostName = "ftp://xx.x.xx.xx"
                .UserName = "user"
                .Password = "password"
                .SshHostKey = "ssh-rsa xxxx xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

            End With

            'Set up the session
            Using session As Session = New Session
                ' Connect
                session.ExecutablePath = Path
                session.Open(sessionOptions)
                Dim transferResult As TransferOperationResult

                ' Upload files
                Dim transferOptions As New TransferOptions

                If (session.Opened) Then

                    transferOptions.TransferMode = TransferMode.Binary

                    transferResult = session.PutFiles(FileUpload1.ToString, "/", True, transferOptions)

                    ' Throw on any error
                    transferResult.Check()

                End If

                ' Print results
                Dim transfer As TransferEventArgs
                For Each transfer In transferResult.Transfers
                    Console.WriteLine("Upload of {0} succeeded", transfer.FileName)
                    Console.Read()
                Next
            End Using

            Return 0
        Catch e As Exception
            Console.WriteLine("Error: {0}", e)

            Return 1
        End Try

    End Function

End Class


Thanks for being patient with me
lynzepiper

dwinn86

When I call ProcessFiles() it is underlined and sayd not declared.

Protected Function ProcessFiles() As String
[/code]
lynzepiper

When is it saying this? What access level does ProcessFiles have?
dwinn86

I am now getting an error saying that ProcessFiles has not been declared.

I am so glad the change was requested now :-P
lynzepiper

dwinn86

Thanks I have got the site now opening, but when I try to upload a file, I select the file to upload but nothing happens.

I have put a message box within the ProcessFiles() function and its not coming out with the message.

It is as if it is not seeing the function call there.

I dont suppose you can advise on this as well?
lynzepiper

lynzepiper

dwinn86

How would I do that?

Public Clas InDirectory Inherits System.Web.UI.Page?

I have just tried that but I get a message saying end of statement expected.

Or does it need to be somewhere else?
lynzepiper

dwinn86

I managed to figure that part out.

I have now got another issue where I load the site, go in to upload the file, but as I get to the form, I get the following error:


Parser Error Message: 'FTPUploadSite.InDirectory' is not allowed here because it does not extend class 'System.Web.UI.Page'.


Its pointing to the following in my InDirectory.aspx page:

Line 1:  <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="InDirectory.aspx.vb" Inherits="FTPUploadSite.InDirectory" %>


Do you know what this could be at all?
dwinn86

I have now done this, added it as a reference, it is now happy with the parameters I am providing.

When I run the website now, i get an error message that says:


Parser Error Message: Could not load type 'FTPUploadSite.Global_asax'.


Pointing to this page:

Line 1:  <%@ Application Codebehind="Global.asax.vb" Inherits="FTPUploadSite.Global_asax" Language="vb" %>


Do you know what this means?
lynzepiper

dwinn86

I see, becasue I havent set up a reference to WinSCP, it wont allow .Hostname, .User etc etc because there are no public members set up yet?

I have done that, gone to the WinSCP on my local drive and can only see DragExt.dll

There are no other .dll files there.

Does that mean I will have to download it?
lynzepiper

dwinn86

No I havent, do I need to add it as a reference from Visual Studio?
lynzepiper

dwinn86

Thanks for that...changed it now.

In my code behind page it is referenced as:

Imports WinSCP


But it is saying that it has no public members of can not be found.

Do you know how this can be rectified?
lynzepiper

dwinn86

Ok then, I have it all back in to the code behind page.

How do I reference WinSCP in my .aspx page?

<%@ Import Namespace="WinSCP" %> ?
lynzepiper

dwinn86

That is not a problem...I am kind of a newbie myself :-)

My codebehind script is as follows:

Imports System.Net

Imports System.IO
Imports WinSCP

Public Class InDirectory

    Protected Function ProcessFiles() As Integer

        Dim Path As String
        Path = "C:\Program Files\WinSCP\WinSCP.exe"

        Try
            ' Setup session options
            Dim sessionOptions As New SessionOptions

            With sessionOptions
                .Protocol = Protocol.sFtp
                .HostName = "xx.x.xx.xx"
                .UserName = "user"
                .Password = "password"
                .FtpMode = FtpMode.Passive
                .SshHostKey = "ssh-rsa xxxx xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

            End With

            'Set up the session
            Using session As Session = New Session
                ' Connect
                session.ExecutablePath = Path
                session.Open(sessionOptions)
                Dim transferResult As TransferOperationResult

                ' Upload files
                Dim transferOptions As New TransferOptions

                If (session.Opened) Then

                    transferOptions.TransferMode = TransferMode.Binary

                    transferResult = session.PutFiles(FileUpload1.SelectedItem, "/", True, transferOptions)

                    ' Throw on any error
                    transferResult.Check()

                End If

                ' Print results
                Dim transfer As TransferEventArgs
                For Each transfer In transferResult.Transfers
                    Console.WriteLine("Upload of {0} succeeded", transfer.FileName)
                    Console.Read()
                Next
            End Using

            Return 0
        Catch e As Exception
            Console.WriteLine("Error: {0}", e)

            Return 1
        End Try

    End Function

End Class


My main .aspx form is as follows:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="InDirectory.aspx.vb" Inherits="FTPUploadSite.InDirectory" %>


<%@ Import Namespace="FTPUploadSite" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            font-family: Arial;
            font-size: xx-large;
        }
    </style>
</head>
<body style="height: 797px; width: 1621px; background-color: #CCFFFF">
    <form id="form1" runat="server">
    <div class="style1" style="text-align: center">
   
        FTP In Directory</div>
    <p>
        &nbsp;</p>
        <script runat="server">
            Protected Sub butUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles butUpload.Click
               
                'Declaring the path of where the file should be uploaded to on the FTP site.
                'Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create("ftp://xx.x.xx.xx/In/" + FileUpload1.FileName), FtpWebRequest)
                Dim objOutlook As Object
                Dim objOutlookMsg As Object

                'If no file has been selected, give error message.
                If FileUpload1.HasFile = False Then
                    MsgBox("A file needs to be selected!")
                End If
                               
                'If a file has been selected, carry out the file upload process.
                If FileUpload1.HasFile = True Then
                    Try
                        ProcessFiles()
                       
                        'ftp.Credentials = New System.Net.NetworkCredential("dwinn", "america86")
                        'ftp.KeepAlive = False
                        'ftp.Timeout = 20000
                        'ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile
                        'ftp.UseBinary = True
                       
                        Const olMailItem = 0
                        'The importance level of the email.
                        Const olImportanceHigh = 1
                        'Who the email is going to.
                        Const olTo = 1

                        objOutlook = CreateObject("Outlook.Application")
                        'Creating new mail item.
                        objOutlookMsg = objOutlook.CreateItem(olMailItem)

                        'Declaring the directory to read the file from.
                        Dim sftpFileStream As New FileStream("C:\" + FileUpload1.FileName, FileMode.Open)
                        'Getting the length of the file.
                        Dim sftpBuffer(sftpFileStream.Length) As Byte
                         
                        MsgBox("Carrying On")
                       
                        'Reading in the file.
                        sftpFileStream.Read(sftpBuffer, 0, sftpFileStream.Length)

                        'Upload the file
                        'Dim ftpGetStream As Stream = ftp.GetRequestStream()
                        'ftpGetStream.Write(ftpBuffer, 0, ftpFileStream.Length)

                        'Closes off connections.
                        'ftpGetStream.Close()
                        'ftpFileStream.Close()
                       
                        'Getting a response from the FTP site.
                        'Dim ftpResponse As FtpWebResponse = CType(ftp.GetResponse(), FtpWebResponse)
                       
                        'SCRIPT TO SEND EMAIL GOES HERE!
                        With objOutlookMsg
                            'The email address of the recipient.
                            Dim objOutlookRecip As Object = .Recipients.Add("dwinn@email.co.uk")
                            objOutlookRecip.type = olTo
                                 
                            'Declaring the subject of the email.
                            .Subject = "FTP File Upload Confirmation"
                            'Declaring what will be in the email.
                            .Body = "Hello, this is confirmation that the file: " + FileUpload1.FileName + " has been uploaded successfully..."
                            'The importance level of the email.
                            .Importance = olImportanceHigh
                            'Sending the email.
                            .send()
                        End With
                        objOutlookMsg = Nothing
                        objOutlook = Nothing
                       
                    Catch ex As Exception

                        MsgBox("File: " + FileUpload1.FileName + " has been uploaded...")
                       
                    End Try
                End If
            End Sub

            Protected Sub butDirectories_Click(ByVal sender As Object, ByVal e As EventArgs) Handles butDirectories.Click
               
                'Takes the user to the FTP Directories screen.
                Response.Redirect("form1.aspx")
               
            End Sub

            Protected Sub butSystemLogOut(ByVal sender As Object, ByVal e As EventArgs) Handles butSysLogOut.Click
               
                'Takes the user to the User Login screen.
                Response.Redirect("form2.aspx")
               
            End Sub
           
            Protected Function ProcessFiles() As Integer

                Dim Path As String
                Path = "C:\Program Files\WinSCP\WinSCP.exe"

                Try
                    ' Setup session options
                    Dim sessionOptions As New SessionOptions

                    With sessionOptions
                        .Protocol = Protocol.sFtp
                        .HostName = "xx.x.xx.xx"
                        .UserName = "user"
                        .Password = "password"
                        .FtpMode = FtpMode.Passive
                        .SshHostKey = "ssh-rsa xxxx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

                    End With

                    'Set up the session
                    Using session As Session = New Session
                        ' Connect
                        session.ExecutablePath = Path
                        session.Open(sessionOptions)
                        Dim transferResult As TransferOperationResult

                        ' Upload files
                        Dim transferOptions As New TransferOptions

                        If (session.Opened) Then

                            transferOptions.TransferMode = TransferMode.Binary

                            transferResult = session.PutFiles(FileUpload1.SelectedItem, "/", True, transferOptions)

                            ' Throw on any error
                            transferResult.Check()

                        End If

                        ' Print results
                        Dim transfer As TransferEventArgs
                        For Each transfer In transferResult.Transfers
                            Console.WriteLine("Upload of {0} succeeded", transfer.FileName)
                            Console.Read()
                        Next
                    End Using

                    Return 0
                Catch e As Exception
                    Console.WriteLine("Error: {0}", e)

                    Return 1
                End Try

            End Function
           
        </script>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p style="text-align: center">
        <asp:FileUpload ID="FileUpload1" runat="server" />
&nbsp;
        </p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        <asp:Button ID="butUpload" runat="server" Text="Upload File" />
    &nbsp;
    &nbsp;<asp:Button ID="Button4" runat="server"
            PostBackUrl="ftp://xx.x.xx.xx/user/In/" style="margin-left: 1px"
            Text="FTP List" />
    &nbsp;&nbsp;
        <asp:Button ID="butDirectories" runat="server" Text="Back to FTP Directories"
            Width="176px" />
&nbsp;&nbsp;
        <asp:Button ID="butSysLogOut" runat="server" Text="Exit the system"
            Width="176px" />
    </p>
    <p style="text-align: center">
        &nbsp;
    </p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
&nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    <p style="text-align: center">
        &nbsp;</p>
    </form>
</body>
</html>


Again, many thanks to you for everything :-)
lynzepiper

dwinn86

I have just moved the script in to my .aspx page and it now accesses the function with no problems but is saying that

Compiler Error Message: BC30002: Type 'SessionOptions' is not defined.


Pointing to this line of code:

Dim sessionOptions As New SessionOptions


Any ideas?

Again, thank you so much for helping me with this.
lynzepiper

dwinn86

I am not passing parameters...I am literally just calling ProcessFiles() in my .aspx page

Would it be wise if I use parameters then?

What I dont understand is that it picks up the function name, but is saying it is not declared.

What if I copy the session code from the code behind page (.aspx.vb) and just paste it under my main upload routine in my .aspx page?
lynzepiper

dwinn86

I have changed it to private, protected and protected friend and I get the same error message.

Also, In the code behind page, im getting an error for .Protocol, .HostName, .UserName, .Password, .FtpMode, .sshHostkey.

Each one is saying that they are not a member of FTPUploadSite.SessionOptions.

What do I need to do to make them members?
lynzepiper

dwinn86

It is called Public Shared Function ProcessFiles() As Integer

It is in the InDirectory.aspx.vb - my code behind class.
lynzepiper

dwinn86

I have just run the site, gone in to upload a file, and before I get to the form, I get an error saying that:

Compiler Error Message: BC30451: 'ProcessFiles' is not declared. It may be inaccessible due to its protection level.


Why is this happening?
dwinn86

Hello,

My ProcessFiles() doesnt require any parameters...I am setting the values of the Hostname, UserName and Password within the function.

I have seen ona few forums that people specify the hostkey as well when creating a session, but I do not know how to get that detail?

Would you be able to advise on that at all?

Many thanks
lynzepiper

dwinn86

No I havent yet.

Do I need to pass it the Hostname, username, password etc?
lynzepiper

dwinn86

I only want to do SFTP.

Ok, this is the code I have for the Upload method in my.aspx page.

Does this look correct? or am I missing something:?


Protected Sub butUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles butUpload.Click

'Declaring the path of where the file should be uploaded to on the FTP site.
'Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create("ftp://XX.X.XX.XX/In/" + FileUpload1.FileName), FtpWebRequest)
Dim objOutlook As Object
Dim objOutlookMsg As Object

'If no file has been selected, give error message.
If FileUpload1.HasFile = False Then
MsgBox("A file needs to be selected!")
End If

'If a file has been selected, carry out the file upload process.
If FileUpload1.HasFile = True Then
Try
ProcessFiles()

Const olMailItem = 0
'The importance level of the email.
Const olImportanceHigh = 1
'Who the email is going to.
Const olTo = 1

objOutlook = CreateObject("Outlook.Application")
'Creating new mail item.
objOutlookMsg = objOutlook.CreateItem(olMailItem)

'Declaring the directory to read the file from.
Dim sftpFileStream As New FileStream("C:\" + FileUpload1.FileName, FileMode.Open)
'Getting the length of the file.
Dim sftpBuffer(sftpFileStream.Length) As Byte

'Reading in the file.
sftpFileStream.Read(sftpBuffer, 0, sftpFileStream.Length)

'SCRIPT TO SEND EMAIL GOES HERE!
With objOutlookMsg
'The email address of the recipient.
Dim objOutlookRecip As Object = .Recipients.Add("emailaddress")
objOutlookRecip.type = olTo

'Declaring the subject of the email.
.Subject = "FTP File Upload Confirmation"
'Declaring what will be in the email.
.Body = "Hello, this is confirmation that the file: " + FileUpload1.FileName + " has been uploaded successfully..."
'The importance level of the email.
.Importance = olImportanceHigh
'Sending the email.
.send()
End With
objOutlookMsg = Nothing
objOutlook = Nothing

Catch ex As Exception

MsgBox("File: " + FileUpload1.FileName + " has been uploaded...")

End Try
End If
End Sub


Thank you once again for your help and patience.

Much appreciated.
lynzepiper

dwinn86

Thank you for that.

To upload the filename specified in my combo box, woul I use: session.PutFiles(UploadFile1.SelectedItem.text, "/", True, transferOptions)

Then in my routine on my.aspx page, I do a call for ProcessFiles()?
lynzepiper

dwinn86

Sorry, as you can tell...I am trying to learn this as not worked with it before.

I areally appreciate your help though, thank you.
dwinn86

I am not calling process files at the moment.

I would need to use that in my routine where I upload the file wouldnt I?
lynzepiper

dwinn86

Sorry, what code would you like to see?

Where I upload the files?
lynzepiper

dwinn86

Hi,

I have now put the code in the code behind page...declared a function that takes the connection details as the parameters.

When I go to declare the connection details: .HostName, .UserName, .Password, I get a message for each saying they are not a member of FTPUploadSite.SessionOptions.

Can you please tell me what I am doing wrong?

My code is as follows:


Imports System.Net
Imports System.IO
Imports WinSCP

Public Class InDirectory
Inherits System.Web.UI.Page

Dim InDirectory As Object

Public Shared Function ProcessFiles(HostName As String, UserName As String, Password As String, LocalPath As String, RemotePath As String) As Integer

Dim Path As String
Path = "C:\Program Files\WinSCP\WinSCP.exe"

Try
' Setup session options
Dim sessionOptions As New SessionOptions

With sessionOptions
.Protocol = Protocol.Sftp
.HostName = "xx.x.xx.xx"
.UserName = "user"
.Password = "password"
End With

'Set up the session
Using session As Session = New Session
' Connect
session.ExecutablePath = Path
session.Open(sessionOptions)

' Upload files
Dim transferOptions As New TransferOptions

If (session.Opened) Then

transferOptions.TransferMode = TransferMode.Binary

Dim transferResult As TransferOperationResult
transferResult = session.PutFiles(FileUpload1.SelectedItem, True, transferOptions)

' Throw on any error
transferResult.Check()

End If

' Print results
Dim transfer As TransferEventArgs
For Each transfer In transferResult.Transfers
Console.WriteLine("Upload 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


Am I setting up the SessionOptions in the wrong place?

Many thanks[/quote]
lynzepiper

dwinn86

Thank you very much for your reply.

I have been looking over your code for the last couple of hours.

Would I need to put this code in to a new class or could I put it all in the subroutine that uploads and downloads the files (.aspx page)?

Many thanks again.
lynzepiper

dwinn86

Hello lynzepiper,

Thank you for your reply.

Would you mind elaborating a little bit more?

Do you mean providing 3 parameters for my function, so it would be: Public Shared Function Main(Hostname as String, User As String, Password As String) As Integer etc?

And then from my .aspx page, within the subroutine that does the upload and download, I call function 'Main' and provide it with the 3 parameters?

Or do you mean something else?

Thanks again
lynzepiper

Modify the code and copy

dwinn86

Code to upload and download files via SFTP using WinSCP

Hi,

I have developed a website that allows users to upload/download files to and from an FTP server.

The requirements have now been changed in that the files need to be uploaded and downloaded using SFTP.

I have downloaded WinSCP and set it up to connect to my FTP server.

I am now stumped though as to what I need to change or add in to my Visual Studio VB.Net project.

I have read that I need to create a SessionOptions class that stores the authentication details, but still dont understand how this is supposed to work.

Below is the code I have:

Imports System

Imports WinSCP
Imports System.Globalization
Imports System.IO

Public Class SessionOptions

    Dim HostName As String
    Dim UserName As String
    Dim Password As String

    Public Shared Function Main() As Integer

        Try
            ' Setup session options
            Dim sessionOptions As New SessionOptions

            With sessionOptions
                '.Protocol = Protocol.Sftp
                .HostName = "XX.XX.XX.XX"
                .UserName = "user"
                .Password = "password"
            End With

            Using session As Session = New Session
                ' Connect
                session.Open(sessionOptions)

                ' Upload files
                Dim transferOptions As New TransferOptions
                transferOptions.TransferMode = TransferMode.Binary

                Dim transferResult As TransferOperationResult
                transferResult = session.PutFiles(FileUpload1.SelectedItem, False, transferOptions)

                ' Throw on any error
                transferResult.Check()

                ' Print results
                Dim transfer As TransferEventArgs
                For Each transfer In transferResult.Transfers
                    Console.WriteLine("Upload 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


How would I now do the code to be able to upload and download files using SFTP from my .aspx forms that I have created.

All help and advice will be much appreciated.

Dwinn86