In this post I am going to put a piece of code I have written for my friend. The requirement was to validate the given username and password are valid for the specified FTP server.
static bool CheckFTPLogin(String ftpServer, uint ftpPort, String userName, String password)
{
if (String.IsNullOrEmpty(ftpServer) ||
String.IsNullOrEmpty(userName) ||
String.IsNullOrEmpty(password))
return false;
using (TcpClient client = new TcpClient())
{
try
{
client.Connect(ftpServer, Convert.ToInt32(ftpPort));
NetworkStream nStream = client.GetStream();
StreamReader myReader = new StreamReader(nStream);
StreamWriter myWriter = new StreamWriter(nStream);
string retValue = myReader.ReadLine();
Console.WriteLine(retValue);
if (retValue.EndsWith("ready.") && retValue.StartsWith("220"))
{
myWriter.WriteLine(string.Format("USER {0}", userName));
myWriter.Flush();
retValue = myReader.ReadLine();
Console.WriteLine(retValue);
if (retValue.StartsWith("331"))
{
myWriter.WriteLine(string.Format("PASS {0}", password));
myWriter.Flush();
retValue = myReader.ReadLine();
Console.WriteLine(retValue);
if (retValue.StartsWith("230"))
{
///Login Success
myReader.Close();
myWriter.Close();
return true;
}
}
else
{
///Login Error.
myReader.Close();
myWriter.Close();
return false;
}
}
else
{
///FTP Connection error.
myReader.Close();
myWriter.Close();
return false;
}
return false;
}
catch
{
///FTP Connection Error
return false;
}
}
}
CheckFTPLogin is a generic method which will return a boolean value true if and only if the username and password are valid credentials in the given ftpServer.
No comments:
Post a Comment