我想动态生成文件并将该文件保存在 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();
最佳答案
我不能 100% 确定我理解正确。
您获得了名为 response 的 FTPWebResponse 对象。您可以为 FTPWebResponse 对象调用 GetResponseStream() 函数。此函数将为您提供可用于进行实际 FTP 传输的流。 不仅仅是编写一个复制函数,从您的 sourceStream StreamReader 复制到一个 Stream。
例子:
FtpWebResponse response = (FtpWebResponse)requestFileUpload.GetResponse();
Stream myFTPStream = response.GetResponseStream();
//copy data into stream
response.Close();
当然你还需要检查exceptiont等等。我也没有检查您的其余代码,但如果到目前为止一切正常,这就是您获得所需流的方式。
关于c# - 如何直接从 FTP 文件夹中的流创建和保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24734316/