2015-07-21 67 views
0

我使用下面的代碼示例將數據上傳到FTP服務器。WebClient.UploadData返回FTP的字節[0]

var streamXml = new MemoryStream(); 
var writer = new StreamWriter(streamXml); 
writer.Write(stringaXml); 
writer.Flush(); 
streamXml.Position = 0; 

var response = client.UploadData(remoteFilePath, ReadFully(streamXml));  
Logger.Info(client.Encoding.GetString(response)); 

public static byte[] ReadFully(Stream input) 
{ 
    var buffer = new byte[16 * 1024]; 
    using (var ms = new MemoryStream()) 
    { 
     int read; 
     while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
     { 
      ms.Write(buffer, 0, read); 
     } 
     return ms.ToArray(); 
    } 
} 

文件傳輸成功,但response總是byte[0]

難道我失去了一些東西?

更新

我修改ReadFully方法是這樣的:

public static byte[] ReadFully(Stream input) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     input.CopyTo(ms); 
     return ms.ToArray(); 
    } 
} 

我的小XML文件被成功保存到FTP服務器,但response仍然byte[0]

回答

-1

我查了RFC的FTP (http://tools.ietf.org/html/rfc959),它說

The data, when transferred in response to FTP service commands, shall always be sent over the data connection, except for certain informative replies. 

看起來它使用另一個端口(默認20)來發送響應,這就是爲什麼你不能接收它。

你沒有提到對象是什麼類型客戶端,但我建議使用內置的FtpWebRequest類進行FTP操作。下面是一個例子,如何用它來上傳文件:MSDN How to: Upload Files with FTP

UPDATE:

我測試的示例代碼上述文章中,我能夠通過FtpWebResponse.StatusDescription如

獲取服務器的響應消息

"226 Successfully transferred \"/newFile.txt\"\r\n"

這正是在OP想

+0

的'WebClient'使用'FTPWebRequest'內部。它自然會處理數據連接端口,否則就沒用了。 –

+0

它不會無用,因爲它有其他用途,顯然FTP只是一種協議。你怎麼知道它在內部使用FtpWebRequest?我檢查了源代碼,並沒有提及FtpWebRequest。在文檔中它只是說「這種方法使用STOR命令上傳FTP資源,對於HTTP資源,使用POST方法」 –

+0

當然,它也支持其他協議。但它支持FTP,這就是要點。而不支持數據連接的FTP支持是無用的。 –

-1

FTP上傳(與HTTP上傳)不能有任何反應的身體。因此WebClient.UploadData從不會爲FTP返回任何內容。

你期望什麼樣的反應?所有FTP服務器返回的是狀態消息。如果它返回成功,則WebClient.UploadData將自動返回。如果它作爲錯誤返回,則WebClient.UploadData將引發狀態消息的異常。

例如:

An unhandled exception of type 'System.Net.WebException' occurred in System.dll

Additional information: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).