创建一个csv文件并将其删除,并将其保存到本地

时间:2016-11-29 15:52:19

标签: vb.net sftp

我的目标是创建一个csv和sftp,而不使用vb​​.net将文件保存在本地计算机上。这是我的创建csv代码:

 Public Sub writeCSV()

     Dim headers = (From header As DataGridViewColumn In 

     DataGridView1.Columns.Cast(Of DataGridViewColumn)() _
          Select header.HeaderText).ToArray

     Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of 

    DataGridViewRow)() _
               Where Not row.IsNewRow _
               Select Array.ConvertAll(row.Cells.Cast(Of 

    DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing,

    c.Value.ToString, ""))

    Using sw As New IO.StreamWriter("foo.csv")

        sw.WriteLine(String.Join(",", headers))

        For Each r In rows

            sw.WriteLine(String.Join(",", r))

        Next

    End Using

    'Process.Start("foo.csv")

    'SFTP("foo.csv")
End Sub

而不是启动和/或保存过程..我想写一个sub,我可以把这个foo.csv sftp到供应商的服务器。这可能吗?此外,SFTP将需要使用密钥而不是密码。

提前致谢,

2 个答案:

答案 0 :(得分:0)

以下代码使用我共同开发的edtFTPnet/PRO来完成您需要的任务:

Sub SendCsvToSFTP(serverAddress As String, userName As String, password As String, fileName As String, csvText As String)

    Using sftp As New EnterpriseDT.Net.Ftp.SecureFTPConnection

        ' Set up the SFTP connection
        sftp.ServerAddress = serverAddress
        sftp.Protocol = EnterpriseDT.Net.Ftp.FileTransferProtocol.SFTP
        sftp.UserName = userName
        sftp.Password = password

        ' Connect to the server
        sftp.Connect()

        Using csvStream As New MemoryStream()
            Using csvWriter As New StreamWriter(csvStream)
                csvWriter.Write(csvText)                    ' Write the CSV text to the writer
                csvWriter.Flush()                           ' Make sure it's all written to the underlying stream
                csvStream.Seek(0, SeekOrigin.Begin)         ' Now wind back to the beginning before uploading

                sftp.UploadStream(csvStream, fileName)      ' Upload the stream
            End Using
        End Using

        ' Close the SFTP connection
        sftp.Close()
    End Using

End Sub

如您所见,它使用SecureFTPConnection类来完成工作。请注意,edtFTPnet / PRO是商业产品,但有30天的试用版。

答案 1 :(得分:-1)

将CSV文件创建为内存流,然后将该内存流发送到FTP服务器。

以下链接显示了向FTP服务器发送内存流:ASP.NET C# upload MemoryStream content via FTPwebRequest issue