2014年5月6日 星期二

VB.NET中使用FTP下載檔案的兩種方法


.net沒有專門處理FTP的類,我們可以通過調用系統自帶的FTP.EXE 或者是調用win32 API中的wininet.dll來完成基本操作。希望以下的代碼能為大家抛磚引玉。

方法一: 使用Ftp.exe ,通過process類來調用它。

Imports System.Diagnostics

...

Public Sub GetFileByCallFtp()

'定義ProcessStartInfo,Process的啟動資訊。

Dim psi As New ProcessStartInfo

'ftp.exe的路徑最好放到設定檔裡。

psi.FileName = "C:\WINNT\system32\ftp.exe"

psi.RedirectStandardInput = False

psi.RedirectStandardOutput = True

'該值指示不使用作業系統Shell程式啟動進程。

psi.UseShellExecute = False

'命令集檔案名.注意,路徑中不能有空格.

Dim fileName As String = "C\ftp.txt"

'-s:FileName表示,從檔中讀取控制命令

psi.Arguments = "-s:" + fileName

Dim proc As Process

proc = Process.Start(psi)

'等待進程完成任務

proc.WaitForExit()

'在主控台輸出結果

Console.WriteLine(proc.StandardOutput)

Console.ReadLine()

End Sub

==============================================================================

ftp.txt 裡的內容

方法二,使用win32 api —— wininet.dll

首先是,api聲明:

因為此測試程式,是VB.NET ConsoleApplication所以,api聲明寫在Module裡,

方法是靜態的。所以沒加Shared關鍵字, 這一點請大家注意。

_
Public Function InternetOpen(ByVal sAgent As String, ByVal LAccessType As Integer, ByVal sProxyName As String, _
ByVal SProxyBypass As String, ByVal lFlags As Integer) As Integer
End Function

_
Public Function InternetConnect(ByVal hInternetSession As Integer, ByVal sServerName As String, _
ByVal nServerPort As Integer, ByVal sUsername As String, _
ByVal sPassword As String, ByVal lService As Integer, _
ByVal lFlags As Integer, ByVal lCoNtext As Integer) As Integer
End Function

_
Public Function FtpGetFile(ByVal hFtpSession As Integer, ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _
ByVal dwFlagsAndAttributes As Integer, ByVal dwFlags As Integer, _
ByVal dwCoNtext As Integer) As Boolean
End Function

_
Public Function InternetCloseHandle(ByVal hInet As Integer) As Integer
End Function

調用:

Public Sub GetFileByCallWininetDLL()
Try
Dim intinet As Integer = InternetOpen(Nothing, 0, Nothing, Nothing, 0)
If intinet > 0 Then

'參數:intinet的session值,ftp位址,埠,使用者名,密碼,lService, lFlags,lCoNtext

Dim intinetconn As Integer = InternetConnect(intinet, "192.168.110.152", 0, "tokiwa", "tokiwa", 1, 0, 0)

If intinetconn > 0 Then

'下載某個檔到指定檔

Dim ret As Boolean = FtpGetFile(intinetconn, "pagerror.gif", "C:\itest.gif", 0, 0, 1, 0)

If ret Then
Console.WriteLine("ok!")
Console.ReadLine()
End If
InternetCloseHandle(intinetconn)
InternetCloseHandle(intinet)
Else
Console.WriteLine("can't connect!")
Console.ReadLine()
End If

Else
Console.WriteLine("ftp wrong!")
Console.ReadLine()
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.ReadLine()
End Try

End Sub

沒有留言:

張貼留言