Analytics
2010年5月27日 星期四
[ASP.NET]VB.NET FTP上傳檔案(VB.NET FTP upload files)
問題
VB.NET FTP上傳檔案
解決方法
C#請參考http://www.dotblogs.com.tw/jeff-yeh/archive/2008/04/09/2652.aspx
記得IIS裡的FTP的寫入權限要開啟歐
Public Shared Sub CopyCSVToFtpPath(ByVal strFileName As String, ByVal strFileContent As String)
'fileName上傳的檔案ex : c:\abc.xml , uploadUrl上傳的FTP伺服器路徑ftp://127.0.0.1,UserName使用者FTP登入帳號 , Password使用者登入密碼
Dim requestStream As Stream = Nothing
Dim fileStream As FileStream = Nothing
Dim uploadResponse As FtpWebResponse = Nothing
Try
Dim pathlocal As String = HttpContext.Current.Server.MapPath("..\down\") '暫存路徑
'存檔路徑
pathlocal += strFileName
Dim swS As New StreamWriter(pathlocal, True, System.Text.Encoding.Default)
swS.WriteLine(strFileContent)
swS.Flush()
swS.Close()
'取得WebConfig裡的設定
Dim Address As String = ConfigurationManager.AppSettings("FTP.Address") & strFileName
Dim UserName As String = ConfigurationManager.AppSettings("FTP.UserName")
Dim Password As String = ConfigurationManager.AppSettings("FTP.Password")
'要給檔案路徑
Dim uploadRequest As FtpWebRequest = DirectCast(WebRequest.Create(Address), FtpWebRequest)
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
'設定Method上傳檔案
uploadRequest.Proxy = Nothing
If UserName.Length > 0 Then
'如果需要帳號登入
Dim nc As New NetworkCredential(UserName, Password)
'設定帳號
uploadRequest.Credentials = nc
End If
requestStream = uploadRequest.GetRequestStream()
FileStream = File.Open(pathlocal, FileMode.Open)
Dim buffer As Byte() = New Byte(1024) {}
Dim bytesRead As Integer
While True
'開始上傳資料流
bytesRead = FileStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then
Exit While
End If
requestStream.Write(buffer, 0, bytesRead)
End While
requestStream.Close()
uploadResponse = DirectCast(uploadRequest.GetResponse(), FtpWebResponse)
fileStream.Flush()
fileStream.Close()
File.Delete(pathlocal)
Catch ex As Exception
'lblMessage.Text = ex.Message
Throw ex
Finally
If uploadResponse IsNot Nothing Then
uploadResponse.Close()
End If
If FileStream IsNot Nothing Then
FileStream.Close()
End If
If requestStream IsNot Nothing Then
requestStream.Close()
End If
End Try
End Sub
訂閱:
張貼留言 (Atom)
5 則留言:
你好:
想請問 "strFileContent" 是要丟入什麼參數?
不太了解它的用途,謝謝你的回答唷. by Jull
"strFileContent" 是檔案內容,此function是用來上傳CSV(逗號分割的文字檔)
通常你可以用File.ReadAllText去讀某檔案
再請教一下,如果要上傳其他檔案格式(ex: doc,jpg,xml......),也可用這樣的方式上傳嗎? 或是需要做什麼調整? 謝謝你唷. by Jull
"strFileName "是檔案的名稱
example:test.txt,text.csv,text.xml
基本上在傳送的過程中,是用byte再傳的,所以文字內容的都可以傳送
但是如果要傳送類似jpg,bmp,exe之類的檔案,要改方式
'這一段是把要上傳的資料寫到站存位置
Dim swS As New StreamWriter(pathlocal, True, System.Text.Encoding.Default)
swS.WriteLine(strFileContent)
swS.Flush()
swS.Close()
因此把上面寫站存檔的方式改成你要的方式就可以了
瞭解了~謝謝你的分享唷~
by Jull
張貼留言