我创建了一个将文件上传到远程 FTP 服务器的应用程序。如果凭据(地址、用户名、密码等)错误,我想抛出一个错误。到目前为止,它从来没有。我的代码有什么问题?当凭据正确时,它会成功上传。
这是我正在使用的课程:
public void upload(string remoteFile, string localFile)
{
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpStream = ftpRequest.GetRequestStream();
FileStream localFileStream = File.OpenRead(localFile);
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesSent != 0)
{
ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
以及我在表单中调用上传函数的位置:
点击按钮 =
ftp ftpClient = new ftp(@"ftp://weburl.com/", "user", "password");
UploadToFTP("testing/file.txt" , @"C:\file.txt");
void UploadToFTP(string FTPfolder, string LocalFolder)
{
try
{
ftpClient.upload(FTPfolder, LocalFolder);
Messagebox.Show("Uploaded Successfully!");
}
catch (Exception ex)
{
Messagebox.Show(ex.ToString());
}
}