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

时间:2016-08-30 10:25:12

标签: c# .net ftp webrequest ftpwebrequest

我正在尝试在FTP服务器上创建一个文件,但我所拥有的只是一个字符串或数据流以及应该用它创建的文件名。有没有办法在流或字符串上创建服务器上的文件(我没有创建本地文件的权限)?

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()) { }

2 个答案:

答案 0 :(得分:8)

只需将您的信息流复制到FTP请求信息流:

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

对于字符串(假设内容是文本):

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

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

如果内容是文本,则应使用文本模式:

request.UseBinary = false;

答案 1 :(得分:-1)

我这样做是为了将一个xml文件发送到FTP。它工作正常。我认为这就是你所需要的。

 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();

问候!