我有一个小的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();
有什么想法吗?
谢谢!
答案 0 :(得分:0)
你必须先调用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();
答案 1 :(得分:0)
我也有这个错误。 (您不需要先获得响应。)在我的情况下,这是FTP服务器上的文件夹权限问题。