简体   繁体   English

将文件从字符串或流上传到 FTP 服务器

[英]Upload a file to an FTP server from a string or stream

I'm trying to create a file on an FTP server, but all I have is either a string or a stream of the data and the filename it should be created with.我正在尝试在 FTP 服务器上创建一个文件,但我所拥有的只是一个字符串或一个数据流以及它应该使用的文件名。 Is there a way to create the file on the server (I don't have permission to create local files) from a stream or string?有没有办法从流或字符串在服务器上创建文件(我没有创建本地文件的权限)?

string location = "ftp://xxx.xxx.xxx.xxx:21/TestLocation/Test.csv";

WebRequest ftpRequest = WebRequest.Create(location);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(userName, password);

string data = csv.getData();
MemoryStream stream = csv.getStream();

//Magic

using (var response = (FtpWebResponse)ftpRequest.GetResponse()) { }

Just copy your stream to the FTP request stream:只需将您的流复制到 FTP 请求流:

Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();

For a string (assuming the contents is a text):对于字符串(假设内容是文本):

byte[] bytes = Encoding.UTF8.GetBytes(data);

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
}

Or even better use the StreamWriter :或者甚至更好地使用StreamWriter

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
    writer.Write(data);
}

If the contents is a text, you should use the text mode:如果内容是文本,则应使用文本模式:

request.UseBinary = false;

i make this for send a xml file to a FTP.我这样做是为了将 xml 文件发送到 FTP。 It works fine.它工作正常。 I thinks is what you need.我认为是你需要的。

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://XXXXXXXXXX//" + filename);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            request.Credentials = new NetworkCredential("user", "pwd");
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;

            StreamReader sourceStream = new StreamReader(file);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

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

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

Regards!问候!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM