用C#在SFTP中保存文件

时间:2017-01-10 14:18:30

标签: c# c#-4.0 c#-3.0

我需要在SFTP中保存以编程方式生成的CSV文件。目前我正在使用以下代码将生成的文件保存在本地PC路径中。 如何提供特定的SFTP路径来保存文件?

        StringBuilder sb = new StringBuilder();

        IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                          Select(column => column.ColumnName);
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in dt.Rows)
        {
            IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
            sb.AppendLine(string.Join(",", fields));              
        }          
        string fileName = "ReportName_" + DateTime.Now.ToString("mmddyyyyhhmmss") + ".csv";   
        File.WriteAllText("E:\\LeafLogix\\ICS\\"+fileName+"", sb.ToString());            
        MessageBox.Show("ok");

1 个答案:

答案 0 :(得分:0)

您可以使用FtpWebRequest中的System.Net对象。

下面的文档显示了该示例:

MSDN 因此,不必通过File.WriteAllText写入文件,而是必须将sb中存储的数据更改为字节,并使用stream.Write([..])上传。

要将string更改为字节,您可以使用Encoding.ASCII.GetBytes(string),而对于UTF8:Encoding.UTF8.GetString("user", 0);