FtpWebRequest question

Can anybody please help me

I am trying to write a code to uplode or delete file on ftp server. A problem is that I don't know how to set up Method property for ftpwebrequest class, so sample code like this would work.

Dim serverUri As String = "ftp://ftp.contoso.com/file.txt"
Dim request As FtpWebRequest = CType(WebRequest.Create(serverUri), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.DeleteFile
request.EnableSsl = True
Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)

Thank you



Answer this question

FtpWebRequest question

  • Michel Péres

    Dear JornDev,

    I think that your problem is on the following line :

    Dim myFTPURI As System.Uri = New System.Uri(My.Settings.ftpServerAddress & "/" & My.Settings.ftpInitialDirectory)

    The parameter passed to the constructor must be a file path, not a directory path.

    if you want for example to upload a local file to a distant file called myFileName.txt :

    Dim myFTPURI As System.Uri = New System.Uri("ftp://ftp.contoso.com/folder1/folder2/.../folderN/myFilename.txt")

    the subdirectories /folder1/folder2/.../folderN/ must already exist in the root directory of the connected user, prior uploading the file.

    Passive mode should also be set to true by default. However some FTP servers require pasive mode to be set to false.

    Best regards



  • AndyReddy

    the sample code you have posted looks correct. what doesn't work about it
    you change the request.Method to DeleteFile or UploadFile depending on what action you want to do. it may help if you could rephrase your question.

    thanks
    tim

  • Plod

    Dear JornDev,

    Did you set the port number in the ftp adress ( like ftp://ftp.contoso.com:26/folder1/folder2/.../folderN/myFilename.txt )

    Next, If you are using TYPSotf FTP Server, you must not use a network share as the entry point of the account user. Instead you must mount a network drive that is associated with this network share, and then you declare that new drive letter as the entry point of your user account.



  • g.miranda

    I've found the problem. The fileserver failed to authenticate IIS on the webserver. I tried uploading a file to a directory on the webserver and it worked just fine. Ergo; the problem is no longer mine =)

    Thank you for taking the time to help me out!

    One more thing though.. Where do I find the output of the System.Net trace Think it might come in handy later on.

    Again, thanks alot man!



  • Bearc0025

    thanks a lot
  • LarsB

    locate the line in the app configuration file:

    initializeData="System.Net.trace.log"

    System.Net.trace.log is the name of the log file that will be automatically created by the trace. This file should be located in the same folder as the application configuration file ( so the folder where the application is located)



  • email2venki

    Yeah, that makes sense. I've made those changes now, which are good, but still same problem.. I've set the UsePassive to false due to the fact that the ftp account is accessible through a custom port.

    The exception acts like before.

    The folder on the ftp server excist, it directs to a network share on another server. The file I'm trying to upload is .jpg image file. Maybe I have to set the binary transfer..

    Thanks for responding so fast! This error is getting on my nerve, hehe.

    Update: I tried to to set the "usebinary" to true, but still the same error..



  • Miroslav Kulha

    dear JornDev,

    You should use the system.net trace to diagnose what is happening.

    Implementing this trace is very easy : you should put the following code in the application configuration file :

    < xml version="1.0" encoding="UTF-8" >

    <configuration>
    <system.diagnostics>
    <trace autoflush="true" />
    <sources>
    <source name="System.Net">
    <listeners>
    <add name="System.Net"/>
    </listeners>
    </source>
    <source name="System.Net.HttpListener">
    <listeners>
    <add name="System.Net"/>
    </listeners>
    </source>
    <source name="System.Net.Sockets">
    <listeners>
    <add name="System.Net"/>
    </listeners>
    </source>
    <source name="System.Net.Cache">
    <listeners>
    <add name="System.Net"/>
    </listeners>
    </source>
    </sources>
    <sharedListeners>
    <add
    name="System.Net"
    type="System.Diagnostics.TextWriterTraceListener"
    initializeData="System.Net.trace.log"
    traceOutputOptions = "DateTime"
    />
    </sharedListeners>
    <switches>
    <add name="System.Net" value="Verbose" />
    <add name="System.Net.Sockets" value="Verbose" />
    </switches>
    </system.diagnostics>
    </configuration>



  • quintas-arias

    Yes, the port number is set. The absoluteURI looks like this:

    ftp://ftp.domain.no:7997/folder/filname.jpg

    I'm using IIS 6 on Windows Server 2003 Web Edition. The target directory is located on a Windows Server 2003 box.

    I tried changing the port to 21. Works much better. There is an error still though. No access to the file, but I think I might be able to fix that. I would like to use another port than 21 though..

    This make any sense to you Can't I use port 7997



  • MABrandt

    I've taken use of your code, and I suspect it works just fine, however.. I get an exception saying:

    "The remote server returned an error: (500) Syntax error, command unrecognized."

    I have made minor alterations to your code. It fails at:

    Dim myFTPStream As System.IO.Stream = myFTPRequest.GetRequestStream()

    And jumps right down to

    Finally

    ' close the input file stream

    If myInputFileStream IsNot Nothing Then

    myInputFileStream.Close()

    myInputFileStream = Nothing

    End If

    End Try

    I guess there might be something wrong with the ftp account or something.. But I can't figure it out. I have control over the FTP server by the way, so I can edit those configurations as well. Here's my complete version of your code:

    Try

    ' open for read the source file

    Dim myInputFileStream As New System.IO.FileStream(fileNameToSave, System.IO.FileMode.Open, System.IO.FileAccess.Read)

    Dim myFileSizeInBytes As Long = myInputFileStream.Length

    Try

    ' get how many bytes is 1% of the file size

    Dim myIncrementInBytes As Long = CLng(CDbl(myFileSizeInBytes) / CDbl(100))

    ' get how many bytes is 0,1% of the file size

    Dim mySmallIncrementInBytes As Long = CLng(CDbl(myFileSizeInBytes) / CDbl(1000))

    Dim myFTPURI As System.Uri = New System.Uri(My.Settings.ftpServerAddress & "/" & My.Settings.ftpInitialDirectory)

    Dim myFTPRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(myFTPURI), System.Net.FtpWebRequest)

    myFTPRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    myFTPRequest.Credentials = New System.Net.NetworkCredential(My.Settings.ftpUsername, My.Settings.ftpPassword, My.Settings.ftpDomain)

    myFTPRequest.UsePassive = False

    Dim myReadBytes As Long = 1

    Dim myBufferLength As Integer = 4096

    Dim myBuffer(myBufferLength) As Byte

    Dim myByteCounter As Long = 0

    Dim mySmallByteCounter As Long = 0

    Dim myProgressValue As Integer = 0

    Dim myFTPStream As System.IO.Stream = myFTPRequest.GetRequestStream()

    ' Upload the file in a try...catch...finally so we are sure to close the stream whatever happens

    Try

    Do While (myReadBytes <> 0)

    myReadBytes = myInputFileStream.Read(myBuffer, 0, myBufferLength)

    myByteCounter += myReadBytes

    mySmallByteCounter += myReadBytes

    If myReadBytes > 0 Then

    myFTPStream.Write(myBuffer, 0, CType(myReadBytes, Integer))

    End If

    If myByteCounter >= myIncrementInBytes Then

    myProgressValue += 1

    myByteCounter = 0

    'System.Threading.Thread.Sleep(100)

    End If

    If mySmallByteCounter >= mySmallIncrementInBytes Then

    mySmallByteCounter = 0

    ' Check for bandwith reduction

    If My.Settings.ftpBandWidthReduction > 0 Then

    System.Threading.Thread.Sleep(My.Settings.ftpBandWidthReduction)

    End If

    End If

    Loop

    Catch ex As Exception

    Throw ex

    Finally

    If myFTPStream IsNot Nothing Then

    myFTPStream.Close()

    Dim myFTPResponse As System.Net.WebResponse = myFTPRequest.GetResponse()

    myFTPResponse.Close()

    myFTPResponse = Nothing

    myFTPStream = Nothing

    myFTPRequest = Nothing

    End If

    End Try

    myProgressValue = 100

    Catch ex As Exception

    Throw ex

    Finally

    ' close the input file stream

    If myInputFileStream IsNot Nothing Then

    myInputFileStream.Close()

    myInputFileStream = Nothing

    End If

    End Try

    Return True

    Catch ex As Exception

    MessageBox.Show(ex.Message)

    Return False

    End Try

    Greatful for any help!!



  • michal krawczyk

    Dear babakl,

    Here is some code ubout uploading a file. This should work only with the .NET 2.0 framework.

    ''' <summary>
    ''' This method makes the core job of sending the file to the FTP server.
    ''' </summary>
    ''' <param name="SourceFilePath">Absolute File path of the file to be send</param>
    ''' <param name="TargetFilePath">absolute FTP Path in the FTP server.</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function StartUpload(ByVal SourceFilePath As String, ByVal TargetFilePath As String) As Boolean
    Try

    If SourceFilePath Is Nothing Then
    Return False
    End If

    If SourceFilePath.Length = 0 Then
    Return False
    End If

    If TargetFilePath Is Nothing Then
    Return False
    End If

    If TargetFilePath.Length = 0 Then
    Return False
    End If

    ' Check if the source file exists
    If Not System.IO.File.Exists(SourceFilePath) Then
    ' remove the file entry from the data provider
    Return False
    End If

    If Not InitSettings() Then
    Return False
    End If

    ' open for read the source file
    Dim myInputFileStream As New System.IO.FileStream(SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
    Dim myFileSizeInBytes As Long = myInputFileStream.Length

    Try
    ' get how many bytes is 1% of the file size
    Dim myIncrementInBytes As Long = CLng(CDbl(myFileSizeInBytes) / CDbl(100))

    ' get how many bytes is 0,1% of the file size
    Dim mySmallIncrementInBytes As Long = CLng(CDbl(myFileSizeInBytes) / CDbl(1000))

    Dim myFTPURI As System.Uri = New System.Uri(TargetFilePath)

    Dim Msg As String = "Trying to contact : '" & private_Settings.DNSorIPAddress & "' on port " & private_Settings.PortNumber
    RaiseEvent OnInfo(Msg)
    System.Windows.Forms.Application.DoEvents()

    Msg = "Login : '" & private_Settings.Login & "'"
    RaiseEvent OnInfo(Msg)
    System.Windows.Forms.Application.DoEvents()

    Msg = "Passive mode : " & private_Settings.PassiveMode.ToString
    RaiseEvent OnInfo(Msg)
    System.Windows.Forms.Application.DoEvents()

    Msg = "BandWith reduction : " & private_Settings.BandWithReduction.ToString
    RaiseEvent OnInfo(Msg)
    System.Windows.Forms.Application.DoEvents()

    Msg = "Destination : '" & myFTPURI.ToString & "'"
    RaiseEvent OnInfo(Msg)
    System.Windows.Forms.Application.DoEvents()

    Dim myFTPRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(myFTPURI), System.Net.FtpWebRequest)
    myFTPRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
    myFTPRequest.Credentials = New System.Net.NetworkCredential(private_Settings.Login, private_Settings.PassWord)
    myFTPRequest.UsePassive = private_Settings.PassiveMode

    Dim myReadBytes As Long = 1
    Dim myBufferLength As Integer = 4096
    Dim myBuffer(myBufferLength) As Byte
    Dim myByteCounter As Long = 0
    Dim mySmallByteCounter As Long = 0
    Dim myProgressValue As Integer = 0

    Dim myFTPStream As System.IO.Stream = myFTPRequest.GetRequestStream()
    ' Upload the file in a try...catch...finally so we are sure to close the stream whatever happens
    Try
    RaiseEvent OnBegin()
    RaiseEvent OnProgress(myProgressValue)
    RaiseEvent OnBytesProcessed(0)
    System.Windows.Forms.Application.DoEvents()

    Do While (myReadBytes <> 0)
    myReadBytes = myInputFileStream.Read(myBuffer, 0, myBufferLength)
    myByteCounter += myReadBytes
    mySmallByteCounter += myReadBytes

    If myReadBytes > 0 Then
    myFTPStream.Write(myBuffer, 0, CType(myReadBytes, Integer))
    End If

    If myByteCounter >= myIncrementInBytes Then
    myProgressValue += 1
    myByteCounter = 0
    RaiseEvent OnProgress(myProgressValue)
    System.Windows.Forms.Application.DoEvents()
    'System.Threading.Thread.Sleep(100)
    End If

    If mySmallByteCounter >= mySmallIncrementInBytes Then
    RaiseEvent OnBytesProcessed(mySmallByteCounter)
    System.Windows.Forms.Application.DoEvents()
    mySmallByteCounter = 0

    ' Check for bandwith reduction
    If private_Settings.BandWithReduction > 0 Then
    System.Threading.Thread.Sleep(private_Settings.BandWithReduction)
    End If
    End If
    Loop

    Catch ex As Exception
    Throw ex

    Finally
    If myFTPStream IsNot Nothing Then
    myFTPStream.Close()

    Dim myFTPResponse As System.Net.WebResponse = myFTPRequest.GetResponse()
    myFTPResponse.Close()
    myFTPResponse = Nothing
    myFTPStream = Nothing
    myFTPRequest = Nothing

    End If
    End Try

    myProgressValue = 100
    RaiseEvent OnProgress(myProgressValue)
    RaiseEvent OnBytesProcessed(mySmallByteCounter)
    RaiseEvent OnEnd()
    System.Windows.Forms.Application.DoEvents()

    Catch ex As Exception
    Throw ex

    Finally
    ' close the input file stream
    If myInputFileStream IsNot Nothing Then
    myInputFileStream.Close()
    myInputFileStream = Nothing
    End If

    End Try

    Return True

    Catch ex As Exception
    Return False

    End Try
    End Function



  • FtpWebRequest question