-1
我想從ftp下載一個.csv文件,然後將數據從下載的文件導入到sql表中。但它給我錯誤「訪問被拒絕的路徑」,但是當我沒有代碼訪問它時,我可以看到這些文件,並且文件也不是從ftp下載的。在VB.NET中拒絕訪問文件夾
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class Form1
Sub Get_File_From_FTP()
Try
Dim RFN = "ftp://someaddress.com/Test.csv"
Dim LFN = "C:\Sample\IncomingFiles\"
Dim FTP As FtpWebRequest = CType(FtpWebRequest.Create(RFN), FtpWebRequest)
FTP.Credentials = New NetworkCredential("ftpdatasandyalexander", "Y$m0z1k30")
FTP.KeepAlive = False
FTP.UseBinary = True
FTP.Method = WebRequestMethods.Ftp.DownloadFile
Using FtpResponse As FtpWebResponse = CType(FTP.GetResponse, FtpWebResponse)
Using ResponseStream As IO.Stream = FtpResponse.GetResponseStream
Using fs As New IO.FileStream(LFN, FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = ResponseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
ResponseStream.Close()
fs.Flush()
fs.Close()
'Log("")
End Using
ResponseStream.Close()
MessageBox.Show("File Downloaded!")
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Sub Import_File_To_SQL()
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Sample\IncomingFiles\Test.csv;Extended Properties=""text;HDR=Yes;FMT=Delimited(;)"";Persist Security Info=False")
ExcelConnection.Open()
Dim expr As String = "Select * From [sheet$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=MMSQL1;Initial Catalog=dbname; User Id=user; Password=pass;"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "tDHL_SortCode"
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
MessageBox.Show("File Imported!")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Sub
Private Sub btndownload_Click(sender As Object, e As EventArgs) Handles btndownload.Click
Call Get_File_From_FTP()
Call Import_File_To_SQL()
End Sub
末級
文件應該下載在那裏,如果同名文件是存在的,然後它會給出錯誤 –
那麼在這種情況下,你可以添加一個代碼來檢查文件是否存在。如果存在,則刪除它。 如果IO.File.Exists(LFN)Then IO.File.Delete(LFN) – Nathu