Link to home
Start Free TrialLog in
Avatar of pointeman
pointemanFlag for United States of America

asked on

FtpWebRequest Double Login?

I would like to consolidate my code so the 'Login' method is called and the FtpWebRequest would no longer be needed in the 'Upload' method. As is, the FTP server logs show 2 logins. Help!

 
public static FtpWebRequest request = null;

public static bool Login()
        {
            try
            {
                request = (FtpWebRequest) WebRequest.Create(new Uri(_uri));
                request.Credentials = new NetworkCredential(_userName, _password);
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary = _useBinary;
                request.EnableSsl = _enableSsl;
                request.KeepAlive = _keepAlive;
                request.UsePassive = _usePassive;
                request.Timeout = _timeOut;

                using (var response = (FtpWebResponse) request.GetResponse())
                {
                    statusMessage(response.StatusDescription);
                }
                
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static void Upload()
        {
            if (Login())
            {
                try
                {
                    request = (FtpWebRequest) WebRequest.Create(_uri + _fileName);
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(_userName, _password);

                    using (var sourceStream = new StreamReader(_filePath + _fileName))
                    {
                        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); 
                        request.ContentLength = fileContents.Length;

                        using (Stream requestStream = request.GetRequestStream())
                        {
                            requestStream.Write(fileContents, 0, fileContents.Length);
                        }
                    }

                    using (var response = (FtpWebResponse) request.GetResponse())
                    {
                        statusMessage(response.StatusDescription);
                    }
                }
                catch (Exception ex)
                {
                    statusMessage(ex.Message);
                }
            }
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pointeman

ASKER

I want a separate 'response' for login. So if login returns false, I now it was a login failure and not a Upload or Download error.
Also trying to eliminate redundant code.
Good point, thank