[英]Uploading a file to a ftp server fails
我有一個小的C#winform,在其中生成一些文本文件,然后將它們移到ftp服務器。 當我嘗試將它們移動到生產服務器時,它在
遠程服務器返回錯誤:(530)未登錄。
如果我使用相同的ftp地址,用戶名和密碼通過cmd / ftp登錄到ftp,一切正常。 我還在機器上安裝了本地ftp服務器,並對其進行了測試,以查看我的代碼是否生成了錯誤,但是在本地它像一個超級按鈕一樣起作用,我只有生產ftp服務器才有問題。 下面是我的代碼,用於連接文件並將其上傳到ftp服務器:
string[] FileName = Directory.GetFiles(outputpath);
foreach (string txtFile in FileName)
{
FileInfo toUpload = new FileInfo(txtFile);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + tbFTPAddress.Text + @"//" + toUpload.Name);
request.Credentials = new NetworkCredential(tbFTPUserName.Text.Trim(), tbFTPPassword.Text.Trim());
request.Method = WebRequestMethods.Ftp.UploadFile;
Stream ftpStream = request.GetRequestStream();
FileStream file = File.OpenRead(txtFile);
int length = 1024;
byte[] buffer = new byte[length];
int bytesRead = 0;
try
{
do
{
bytesRead = file.Read(buffer, 0, length);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
file.Close();
ftpStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error encountered!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (file != null) file.Close();
if (ftpStream != null) ftpStream.Close();
}
}
錯誤發生在: Stream ftpStream = request.GetRequestStream();
有任何想法嗎?
謝謝!
您必須首先調用GetResponse()。
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);
try
{
//You have to call this or you would be unable to get a stream :)
WebResponse response = fwr.GetResponse();
}
catch (Exception e)
{
throw e;
}
FileStream fs = new FileStream(localfile), FileMode.Open);
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));
fs.Flush();
fs.Close();
//Now you are able to open a Stream
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
request.Abort();
我也有這個錯誤。 (您不需要首先獲取響應。)就我而言,這是FTP服務器上的文件夾權限問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.