Crmgo Blog

vb 2010 ftp

vb 2010 ftp

Тип WebRequestMethods.Ftp ima sledeće članove. Polja Ime Opis AppendFile Predstavlja metodu protokola FTP APPE, koja se koristi za dodavanje fajla na postojeći fajl na FTP serveru. DeleteFile Predstavlja metodu protokola FTP DELE, koja se koristi za brisanje fajla na FTP serveru. DownloadFile Predstavlja metodu…

vb 2010 ftp

Тип WebRequestMethods.Ftp pruža sledeće članove.

Ime Opis
Javno poljeStatički član AppendFile Predstavlja FTP metod APPE koji se koristi za dodavanje sadržaja fajla na postojeći fajl na FTP serveru.
Javno poljeStatički član DeleteFile Predstavlja FTP metod DELE koji se koristi za brisanje fajla na FTP serveru.
Javno poljeStatički član DownloadFile Predstavlja FTP metod RETR koji se koristi za preuzimanje fajla sa FTP servera.
Javno poljeStatički član GetDateTimestamp Predstavlja FTP metod MDTM koji se koristi za dobijanje vremenske oznake fajla na FTP serveru.
Javno poljeStatički član GetFileSize Predstavlja FTP metod SIZE koji se koristi za dobijanje veličine fajla na FTP serveru.
Javno poljeStatički član ListDirectory Predstavlja FTP metod NLIST koji vraća kratak spisak fajlova na FTP serveru.
Javno poljeStatički član ListDirectoryDetails Predstavlja FTP metod LIST koji vraća detaljan spisak fajlova na FTP serveru.
Javno poljeStatički član MakeDirectory Predstavlja FTP metod MKD koji kreira direktorijum na FTP serveru.
Javno poljeStatički član PrintWorkingDirectory Predstavlja FTP metod PWD koji prikazuje ime trenutnog radnog direktorijuma.
Javno poljeStatički član RemoveDirectory Predstavlja FTP metod RMD koji briše direktorijum.
Javno poljeStatički član Rename Predstavlja FTP metod RENAME koji preimenuje direktorijum.
Javno poljeStatički član UploadFile Predstavlja FTP metod STOR koji otprema fajl na FTP server.
Javno poljeStatički član UploadFileWithUniqueName Predstavlja FTP metod STOU koji otprema fajl sa jedinstvenim imenom na FTP server.
primer:
''' <summary>
02 ''' Methods to upload file to FTP Server
03 ''' </summary>
04 ''' <param name="_FileName">local source file name</param>
05 ''' <param name="_UploadPath">Upload FTP path including Host name</param>
06 ''' <param name="_FTPUser">FTP login username</param>
07 ''' <param name="_FTPPass">FTP login password</param>
08 Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
09     Dim _FileInfo As New System.IO.FileInfo(_FileName)
10
11     ' Create FtpWebRequest object from the Uri provided
12     Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
13
14     ' Provide the WebPermission Credintials
15     _FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
16
17     ' By default KeepAlive is true, where the control connection is not closed
18     ' after a command is executed.
19     _FtpWebRequest.KeepAlive = False
20
21     ' set timeout for 20 seconds
22     _FtpWebRequest.Timeout = 20000
23
24     ' Specify the command to be executed.
25     _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
26
27     ' Specify the data transfer type.
28     _FtpWebRequest.UseBinary = True
29
30     ' Notify the server about the size of the uploaded file
31     _FtpWebRequest.ContentLength = _FileInfo.Length
32
33     ' The buffer size is set to 2kb
34     Dim buffLength As Integer = 2048
35     Dim buff(buffLength - 1) As Byte
36
37     ' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
38     Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
39
40     Try
41         ' Stream to which the file to be upload is written
42         Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
43
44         ' Read from the file stream 2kb at a time
45         Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
46
47         ' Till Stream content ends
48         Do While contentLen <> 0
49             ' Write Content from the file stream to the FTP Upload Stream
50             _Stream.Write(buff, 0, contentLen)
51             contentLen = _FileStream.Read(buff, 0, buffLength)
52         Loop
53
54         ' Close the file stream and the Request Stream
55         _Stream.Close()
56         _Stream.Dispose()
57         _FileStream.Close()
58         _FileStream.Dispose()
59     Catch ex As Exception
60         MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
61     End Try
62 End Sub

Evo jednostavnog primera koji pokazuje kako koristiti gornju metodu (UploadFile) za otpremanje fajla na FTP server.

1 ' Upload file using FTP
2 UploadFile("c:\UploadFile.doc", "ftp://FTPHostName/UploadPath/UploadFile.doc", "UserName", "Password")
Pregledajte foldere na serveru:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim arr() As String
        Const username As String = ""
        Const password As String = ""
        Dim request As Net.FtpWebRequest = Net.WebRequest.Create("ftp://ftp.microsoft.com/")
        request.Credentials = New Net.NetworkCredential(username, password)
        request.Method = Net.WebRequestMethods.Ftp.ListDirectoryDetails

        Dim response As Net.FtpWebResponse = request.GetResponse()
        Dim responseStream As Stream = response.GetResponseStream()
        Dim reader As StreamReader = New StreamReader(responseStream)
        Dim lol As String
        Do
            lol = reader.ReadLine
            If Len(lol) < 1 Then Exit Do
            arr = Split(lol, vbNewLine)
            For i = 0 To UBound(arr)
                If Len(arr(i)) > 0 Then
                    ListBox3.Items.Add(arr(i))
                    TextBox1.Text = arr(i)  'just testing it on a textbox
                End If
            Next
        Loop

        MessageBox.Show("Directory List Complete, status {0}", response.StatusDescription)

        reader.Close()
        response.Close()

######### копирование нескольких файлов на ftp

Imports System.Net 
Imports System.IO 
Imports System.Text 
Imports System.Threading 
Public Class Form1 
    Dim thread1 As Thread 
    Dim thread2 As Thread 
    Dim filelist As New List(Of String) 
    Dim myThreadDelegate As New ThreadStart(AddressOf upload) 
    Dim mc As New MyClass1 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
        For i As Integer = 0 To filelist.Count - 1 
            Dim td As Thread = New Thread(New ThreadStart(AddressOf upload)) 
            td.Start()
        Next 
    End Sub 
    Private Sub upload() 
        If (mc.Number > 0) Then 
            mc.Number = mc.Number - 1
            Dim str As String = filelist.Item(mc.Number).Substring(filelist.Item(mc.Number).IndexOf("\")) 
            Dim request As FtpWebRequest = CType(WebRequest.Create("ftp://localhost:22/" & str), FtpWebRequest) 
            With request 
                .Method = WebRequestMethods.Ftp.UploadFile
            End With 
            Dim sourceStream As New StreamReader(filelist.Item(mc.Number)) 
            Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()) 
            sourceStream.Close()
            request.ContentLength = fileContents.Length
            Try 
                Dim flags As Boolean = True 
                Dim currentposition As Long = 0 
                Dim len As Integer = 0 
                Dim requestStream As Stream = request.GetRequestStream() 
                requestStream.Write(fileContents, 0, fileContents.Length)
                requestStream.Close()
                Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse) 
                Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription) 
                response.Close()
            Catch ex As Exception 
                MessageBox.Show(ex.Message + ex.StackTrace.ToString)
            End Try 
        End If 
    End Sub 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
        filelist.AddRange(New String() {"c:\test.txt", "c:\test.csv"}) 
        mc.Number = 2
    End Sub 
End Class 
Public Class MyClass1 
    Private m_number As Integer 
    Public Property Number() As Integer 
        Get 
            SyncLock Me 
                Return m_number 
            End SyncLock 
        End Get 
        Set(ByVal value As Integer) 
            SyncLock Me 
                m_number = value
            End SyncLock 
        End Set 
    End Property 
End Class

Napomena: tekst može biti uz pomoć AI uz ljudsku proveru. Odgovoran: Dmytro Lomaka, Kaltenkirchen.