从FTP下载文件作为流,无法作为文件流打开?

时间:2018-11-16 19:21:03

标签: c# ftp

我使用了一个名为fluentFTP的库来获取要下载(.csv)和上传的文件列表。

我首先连接,然后将文件下载到Stream对象(强制这样做),然后另存为数据集。

        ftpClient.Connect();
        var stream = ftpClient.OpenRead(filePath);
        var config = new ExcelDataSetConfiguration { ConfigureDataTable = _ => new ExcelDataTableConfiguration { UseHeaderRow = true } };
        IExcelDataReader excelReader = ExcelReaderFactory.CreateCsvReader(stream);

当excelReader尝试打开Stream对象时,出现以下错误。我认为是因为CreateCsvReader接受FileStream对象而不是Stream。

System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'

我没有看到返回FileStream的方法,是我搞砸了还是有办法将该Stream对象转换为FileStream。下载的文件是.CSV文件

我可以尝试其他优质的FTP客户端吗?我的大多数连接都是SFTP,可以正常工作,因为SSH.NET提供了一种返回文件流的方法。不幸的是,sftp无法与ftp一起使用,因为它的协议完全不同

1 个答案:

答案 0 :(得分:1)

查看FluentFTP文档并遵循其示例:

https://github.com/robinrodricks/FluentFTP/blob/master/FluentFTP.Examples/BeginOpenRead.cs

namespace Examples {
    public static class BeginOpenReadExample {
        static ManualResetEvent m_reset = new ManualResetEvent(false);

        public static void BeginOpenRead() {
            // The using statement here is OK _only_ because m_reset.WaitOne()
            // causes the code to block until the async process finishes, otherwise
            // the connection object would be disposed early. In practice, you
            // typically would not wrap the following code with a using statement.
            using (FtpClient conn = new FtpClient()) {
                m_reset.Reset();

                conn.Host = "localhost";
                conn.Credentials = new NetworkCredential("ftptest", "ftptest");
                conn.BeginOpenRead("/path/to/file",
                    new AsyncCallback(BeginOpenReadCallback), conn);

                m_reset.WaitOne();
                conn.Disconnect();
            }
        }

        static void BeginOpenReadCallback(IAsyncResult ar) {
            FtpClient conn = ar.AsyncState as FtpClient;

            try {
                if (conn == null)
                    throw new InvalidOperationException("The FtpControlConnection object is null!");

                using (Stream istream = conn.EndOpenRead(ar)) {
                    byte[] buf = new byte[8192];
                    ...