此方法将文件上传到ftp服务器并且工作正常,但在上传到服务器空白行的文本文件中出现在每行之后(“cr lf”出现),例如:
File:
First line
Second line
Third line
Uploaded file:
First line
Second line
Third line
Origin和上传的文件因此具有不同的大小,非文本文件是相同的。
代码:
private void sendFile(string In, string Out)
{
FtpWebRequest request = (FtpWebRequest) WebRequest.Create("ftp://domain//" + Out);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
FileStream sourceStream = new FileStream(In, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] fileContents = new byte[sourceStream.Length];
sourceStream.Read(fileContents, 0, (int) sourceStream.Length);
sorceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
}
我该如何解决这个问题?
答案 0 :(得分:2)
您应该将FtpWebRequest.UseBinary
设置为true,以便保留确切的文件内容。否则,这两个系统将尝试自己计算出行结束,并根据需要更改行终止符。我很少认为这是个好主意。 (编辑:默认情况下,UseBinary
实际上是true
,但这听起来像是使用文字模式引入的问题的种 ...这显然没有任何害处。)
此外:
FileStream
声明using
using
声明Stream.Read
的结果 - 它不必总是一次性读取所有请求的数据File.ReadAllBytes
一次只读取完整的文件数据,或使用Stream.CopyTo
(如果您使用的是.NET 4)将FileStream
复制到请求流(当然不会设置内容长度;我不知道这是否有问题)GetResponse
;目前还不清楚如果你从未获取FtpWebRequest
所以我可能会使用:
private void SendFile(string inputFile, string outputPath)
{
FtpWebRequest request = (FtpWebRequest) WebRequest.Create
("ftp://domain//" + outputPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.Credentials = new NetworkCredential("username", "password");
byte[] fileContents = File.ReadAllBytes(inputFile);
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
// This *may* be necessary in order to validate that everything has happened
using (WebResponse response = request.GetResponse())
{
}
}
答案 1 :(得分:2)
奇怪。我面临同样的问题,直到我没有在文件中提供扩展名,我才能解决它。例如,如果我的文件名是
abcfile
然后我将其设为abcfile.dat,之后它将上传的文件显示为实际文件。我再次使用abcfile.txt上传文件,但这次我的上传文件中出现空行问题。
我建议除了.txt以外,你必须为你的文件提供扩展名。
答案 2 :(得分:1)
您要发送的系统使用系统使用的不同行结尾。我可以假设,因为你得到了一个额外的行,你在Windows上,它使用CRLF结尾。您发送的系统将CR和LF识别为单独的结尾,因此您可以获得额外的行。
对于文本,截断LF或CR,看看会发生什么。我不清楚不同的文件大小。
答案 3 :(得分:0)
在 FileZilla 的顶部菜单中,设置:
Transfer menu > Transfer type > binary