• کد آپلود فایل به سرور FTP
    #1
    Note 
    سلام روز بخیر
    با این کد میتونید فایل ها رو تو سرور FTP آپلود کنید که خیلی نیاز میشه. :yeah:

    [VB]''' <summary>
    ''' Methods to upload file to FTP Server
    ''' </summary>
    ''' <param name="_FileName">local source file name</param>
    ''' <param name="_UploadPath">Upload FTP path including Host name</param>
    ''' <param name="_FTPUser">FTP login username</param>
    ''' <param name="_FTPPass">FTP login password</param>
    Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
    Dim _FileInfo As New System.IO.FileInfo(_FileName)

    ' Create FtpWebRequest object from the Uri provided
    Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)

    ' Provide the WebPermission Credintials
    _FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)

    ' By default KeepAlive is true, where the control connection is not closed
    ' after a command is executed.
    _FtpWebRequest.KeepAlive = False

    ' set timeout for 20 seconds
    _FtpWebRequest.Timeout = 20000

    ' Specify the command to be executed.
    _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    ' Specify the data transfer type.
    _FtpWebRequest.UseBinary = True

    ' Notify the server about the size of the uploaded file
    _FtpWebRequest.ContentLength = _FileInfo.Length

    ' The buffer size is set to 2kb
    Dim buffLength As Integer = 2048
    Dim buff(buffLength - 1) As Byte

    ' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
    Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

    Try
    ' Stream to which the file to be upload is written
    Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

    ' Read from the file stream 2kb at a time
    Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

    ' Till Stream content ends
    Do While contentLen <> 0
    ' Write Content from the file stream to the FTP Upload Stream
    _Stream.Write(buff, 0, contentLen)
    contentLen = _FileStream.Read(buff, 0, buffLength)
    Loop

    ' Close the file stream and the Request Stream
    _Stream.Close()
    _Stream.Dispose()
    _FileStream.Close()
    _FileStream.Dispose()
    Catch ex As Exception
    MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
    End Sub
    [/VB]

    نحوه استفاده:
    [VB]' Upload file using FTP
    UploadFile("c:\UploadFile.doc", "ftp://FTPHostName/UploadPath/UploadFile.doc", "UserName", "Password")
    [/VB]

    موفق باشید

    پاسخ
    ایجاد موضوع جدید   پاسخ به موضوع  

    کاربرانِ درحال بازدید از این موضوع:   1 مهمان