【问题标题】:How do I create and save file from stream on FTP folder directly?如何直接从 FTP 文件夹中的流创建和保存文件?
【发布时间】:2014-07-14 10:20:19
【问题描述】:

我想动态生成文件并将该文件保存在 FTP 文件夹位置

我尝试如下。 我不想在本地保存文件然后上传到 FTP 位置。

我有流并想使用该流在 ftp 上创建文件。

我该怎么做?

  FtpWebRequest requestFileUpload = (FtpWebRequest)WebRequest.Create("ftp://" +ftpServerIP+ "/" + remoteDir);
                    requestFileUpload.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    requestFileUpload.Method = WebRequestMethods.Ftp.UploadFile;

                    // Copy the contents of the file to the request stream.
                    StreamReader sourceStream = new StreamReader(FILEDATA);
                    //FILEDATA is nothing but string
                    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                    sourceStream.Close();
                    requestFileUpload.ContentLength = fileContents.Length;

                    Stream requestStream = requestFileUpload.GetRequestStream();
                    requestStream.Write(fileContents, 0, fileContents.Length);
                    requestStream.Close();

                    FtpWebResponse response = (FtpWebResponse)requestFileUpload.GetResponse();


                    response.Close();

【问题讨论】:

    标签: c# csv ftp c#-3.0 ftpwebrequest


    【解决方案1】:

    我不是 100% 确定我理解正确。

    您获得了名为 response 的 FTPWebResponse 对象。您可以为 FTPWebResponse 对象调用 GetResponseStream() 函数。此功能将为您提供可用于进行实际 FTP 传输的流。 不仅仅是编写一个从 sourceStream StreamReader 复制到 Stream 的复制函数。

    例子:

    FtpWebResponse response = (FtpWebResponse)requestFileUpload.GetResponse();
    
    Stream myFTPStream = response.GetResponseStream();
    
    //copy data into stream
    
    response.Close();
    

    当然你还需要检查异常等等。我也没有检查您的其余代码,但如果到目前为止它工作正常,这就是您获得所需流的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多