none
Error while uploading a file on ftp server..

    General discussion

  • Hi All,

              I am uploading a file on ftp server. I am getting following error.

    The remote server returned an error: (530) Not logged.

    and this error is not predictable for me .

    I don't know why its happening.

    I am using currect password and login. here is my code.

    Please help me.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.IO;
    using System.Threading;
    
    namespace TroboAki
    {
        public partial class ExportFtpDialog : Form
        {
            
            #region StructFtpExport
            private struct FtpExport
            {
                #region Variables
                /* string[] */
                public string[] filesName { get; set; }
    
                /* string */
                public string fileNameUploading { get; set; }
                public string exportDestininationDiretoryPath { get; set; }
                public string login { get; set; }
                public string password { get; set; }
                public string path { get; set; }
                public string message1 { get; set; }
                public string message2 { get; set; }
                public string method { get; set;  }
    
                private string url { get; set; }
    
                /* Uri */
                public Uri serverUri { get; set; }
    
                /* FtpWebREquest */
                public FtpWebRequest request { get; set; }
    
                /* FileStream */
                public FileStream stream { get; set; }
    
                /* Stream */
                public Stream reqStream { get; set; }
    
                /* bool */
                public bool errorConnexion { get; set; }
                public bool errorSimpleConnectionEstablishment { get; set; }
                public bool errorFtpSwitchConnectionEstablishment { get; set; }
                public bool errorFtpMethod { get; set; }
                public bool errorFtpUpload { get; set; }
                public bool errorFtpDeleteFiles { get; set; }
                
                public bool cancel { get; set; }
                public bool passive { get; set; }
    
                /* uint */
                public uint cptFileName { get; set; }
    
                /* ulong */
                public ulong lengthFilesTotal { get; set; }
    
                /* int */
                public int nbSection { get; set; }
                #endregion
    
                #region Constructor
                /* constructor */
    
                public FtpExport(string[] NameFile, string DestininationDiretoryPath, string troboSchoolID)
                    : this()
                {
                    // Setup Files configuration
                    nbSection = NameFile.Length;
                    filesName = NameFile;
                    exportDestininationDiretoryPath = DestininationDiretoryPath;
    
                    // Indicate the current file
                    cptFileName = 1;
    
                    // Setup error
                    errorConnexion = false;
                    errorSimpleConnectionEstablishment = false;
                    errorFtpSwitchConnectionEstablishment = false;
                    errorFtpMethod = false;
                    errorFtpUpload = false;
                    errorFtpDeleteFiles = false;
                    cancel = false;
    
                    // Setup connexion configuration
                    url = TroboAki.Properties.Settings.Default.FtpHost; ;
                    serverUri = new Uri(url);
    
                    login = TroboAki.Properties.Settings.Default.FtpLogin;
                    password = TroboAki.Properties.Settings.Default.FtpPswd;
                    path = DestininationDiretoryPath + "\\";
    
                    // Upload by default
                    method = "UploadFile";
    
                    // Determine the total size of exported files
                    lengthFilesTotal = Get_lengthFilesTotal(nbSection, troboSchoolID);
    
                    // Setup : request, file stream, request stream for the file we will uploading
                    request = null;
                    stream = null;
                    reqStream = null;
                }
    
                private ulong Get_lengthFilesTotal(int nbSection, string troboSchoolID)
                {
                    ulong length = 0;
    
                    for (int i = 0; i < nbSection; i++)
                    {
                         string nameFile = filesName[i];
                        filesName[i]=UserInput.SanitizeString(troboSchoolID) + "_" + UserInput.SanitizeString(filesName[i]);
                        FileStream stream = File.OpenRead(path + filesName[i]);
                        length += (ulong)stream.Length;
                    }
    
                    return length;
                }
                #endregion
            }
            #endregion
    
            #region Variables
            ulong exportedValue = 0;
            ulong uploadValue = 0;
    
            delegate void T(string message);
            T statusUpload1;
            T statusUpload2;
    
            delegate void V(string curentFile, string totalFile);
            V nbFilesUpload;
            #endregion
    
    
            public ExportFtpDialog(ref string[] fileName, ref string exportDestinationDirectoryPath, ref string troboSchoolID)
            {
                InitializeComponent();
    
                statusUpload1 = new T(statusDisplay1);
                statusUpload2 = new T(statusDisplay2);
                nbFilesUpload = new V(nbFilesDisplay);
    
                if (fileName == null || exportDestinationDirectoryPath == "")
                {
                    this.StatusUploadLabel1.Text = "Erreur : impossible de récupérer le(s) nom(s) ou la déstination de(s) fichier(s) exporté(s)";
                    this.AnnulButton.Enabled = false;
                    this.LeaveButton.Enabled = true;
                }
                else
                {
                    // Creating object array to pass in method argument
                    // Creating string array with the name(s) file(s) exported and destination directory path to pass in method argument
                    // The RunWorkerAsync method takes only one argument
                    object[] object_method = new object[3];
                    object_method[0] = fileName;
                    object_method[1] = exportDestinationDirectoryPath;
                    object_method[2] = troboSchoolID;
    
                    // Call the method that will make new thread
                    ExportFtpBgw.RunWorkerAsync(object_method);
                }
            }
    
            #region Button and Display
            private void AnnulButton_Click(object sender, EventArgs e)
            {
                ExportFtpBgw.CancelAsync();
    
                this.AnnulButton.Enabled = false;
                this.LeaveButton.Enabled = true;
            }
    
            private void LeaveButton_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    
            private void statusDisplay(string message1, string message2)
            /*
             * If the control handle has not yet been created, this function wait until it has been created 
             * before calling Invoke.
            */
            {
                int cpt = 0;
                do
                {
                    try
                    {
                        Invoke(statusUpload1, new object[] { message1 });
                        Invoke(statusUpload2, new object[] { message2 });
                    }
                    catch (Exception)
                    {
                        if (cpt > 1000)
                        {
                            return;
                        }
                        else
                        {
                            cpt++;
                        }
                    }
                } while (!IsHandleCreated);
            }
    
            private void statusDisplay1(string message)
            {
                this.StatusUploadLabel1.Text = message;
            }
    
            private void statusDisplay2(string message)
            {
                this.StatusUploadLabel2.Text = message;
            }
    
            private void FilesDisplay(string curentFile, string totalFile)
            {
                int cpt = 0;
                do
                {
                    try
                    {
                        Invoke(nbFilesUpload, new object[] { curentFile, totalFile });
                    }
                    catch (Exception)
                    {
                        if (cpt > 1000)
                        {
                            return;
                        }
                        else
                        {
                            cpt++;
                        }
                    }
                } while (!IsHandleCreated);            
            }
    
            private void nbFilesDisplay(string curentFile, string totalFile)
            {
                this.NbFilesUploadLabel.Text = curentFile + "/" + totalFile;
            }
            #endregion
    
            #region ExportFtpBgw
            private void ExportFtpBgw_DoWork(object sender, DoWorkEventArgs e)
            /*
             * It's in the DoWork  event we call Traetment method (ExportFtp)
             * 1) Recovery of the BackgroundWorker object that triggered the event provided by the sender object
             * 2) Passing arguments by the Argument property of DoWorkEventArgs
            */
            {
                BackgroundWorker worker = sender as BackgroundWorker;
    
                FtpExport ftpExport = new FtpExport();
    
                bool fileExported = false;
                bool run = true;
    
                object[] object_method = new object[2];
                object_method = (object[])e.Argument;
    
                string[] filesName = (string[])object_method[0];
                string exportDestininationDiretoryPath = (string)object_method[1];
                string troboSchoolID = (string)object_method[2];
                
                try
                {
                    ftpExport = new FtpExport(filesName, exportDestininationDiretoryPath, troboSchoolID);
                }
                catch (Exception ex)
                {
                    statusDisplay("Erreur lors du démarrage du télécharement:", ex.Message);
                    run = false;
                }
    
                if (run == true)
                {
                    fileExported = Export(ref ftpExport, worker, e);
                }
            }
    
            private void ExportFtpBgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            /*
             * To use this ReportsProgress BackGroundWorker property must be set to true
             * This event is called whenever the object sender called ReportProgress function
             * The ReportProgress method accepts an integer argument wich should be the percentage of progress
            */
            {
                this.FtpProgressBar.Value = e.ProgressPercentage;
                this.PercentLabel.Text = e.ProgressPercentage.ToString() + " %";
            }
    
            private void ExportFtpBgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            /*
             * This event is called when the worker thread will be completed
             * when the thread finishes the code in the DoWork event
            */
            {
                if ((e.Error != null))
                {
                    this.StatusUploadLabel1.Text = "Opération avortée : il y a eu un problème durant le téléchargement";
                    this.LeaveButton.Enabled = true;
                    this.AnnulButton.Enabled = false;
                }
                else
                {
                    // Uploading success
                    this.LeaveButton.Enabled = true;
                    this.AnnulButton.Enabled = false;
                }
            }
            #endregion
    
            #region ExportFtp
            private bool Export(ref FtpExport ftpExport, BackgroundWorker worker, DoWorkEventArgs e)
            /*
             * Main function to export files
            */
            {
                bool export = false;
                bool connexion = false;
                bool upload = false;
                bool stopExport = false;
                bool deleteFile = false;
    
                int nbConnexionAttempt = 0;
                int[] time = new int[5] { 15000, 15000, 15000, 15000, 15000 };
                //int[] time = new int[5] { 60000, 300000, 900000, 1800000, 3600000 };
    
                string exportDestinationDirectoryPath = ftpExport.exportDestininationDiretoryPath;
                string[] Delay = new string[5] { "1 min", "5 min", "15 min", "30 min", "1h" };
    
                statusDisplay("Démarrage...", "");
    
                do
                {
    
                NewConnexion:
    
                    connexion = FtpConnexion(ref ftpExport);
    
                    if (connexion)
                    {
                        // Reset connexion attempt
                        nbConnexionAttempt = 0;
    
                        ftpExport.fileNameUploading = ftpExport.filesName[ftpExport.cptFileName - 1];
                        FilesDisplay(ftpExport.cptFileName.ToString(), ftpExport.nbSection.ToString());
    
                        // Check if  a request for cancellation is not in
                        if (!ftpExport.cancel)
                        {
                            upload = FtpUpload(ref ftpExport, worker, e);
                        }
    
                        // Chack if the file(s) uploaded
                        if (upload)
                        {
                            // Increments the counter for the next file
                            ftpExport.cptFileName++;
    
                            ftpExport.message1 = "Fichier(s) exporté(s) sur le serveur FTP avec succès";
                            ftpExport.message2 = "";
    
                            export = true;
                        }
                        else if (ftpExport.errorFtpUpload)
                        {
                            goto NewConnexion;
                        }
                        else if (ftpExport.cancel)
                        {
                            stopExport = true;
    
                            deleteFile = FtpDeleteFiles(ref ftpExport);
    
                            export = false;
                        }
                        else
                        {
                            ftpExport.message1 = "Une erreur est survenue lors du téléchargement";
                            ftpExport.message2 = "Opération arreté";
    
                            stopExport = true;
                            export = false;
                        }
                    }
                    else
                    {
                        if ((ftpExport.errorConnexion) || (ftpExport.errorFtpMethod))
                        {
                            statusDisplay(ftpExport.message1, ftpExport.message2);
                            stopExport = true;
                        }
                        else if (nbConnexionAttempt < 5)
                        {
                            statusDisplay(ftpExport.message1, "Nouvelle tentative d'envoi dans : " + Delay[nbConnexionAttempt]);
                            FtpWait(time[nbConnexionAttempt]);
                            nbConnexionAttempt++;
                            goto NewConnexion;
                        }
                        else
                        {
                            ftpExport.message1 = "Impossible de se connecter au serveur, veuillez réessayer ultérieurement";
                            ftpExport.message2 = "";
    
                            stopExport = true;
                            export = false;
                        }
                    }
                } while ((ftpExport.cptFileName <= ftpExport.nbSection) && (!stopExport));
    
                statusDisplay(ftpExport.message1, ftpExport.message2);
    
                return export;
            }
    
            private void FtpWait(int delay)
            /*
            /*
             * Wait function, if there is a break connection the thread is sleeping during a delay
             * defines in the Export function.
             * The sleep method of the class Thread is blocking method
            */
            {
                Thread.Sleep(delay);
            }
    
            private bool FtpConnexion(ref FtpExport ftpExport)
            /*
             * Get the transmission mode and call the appropriate function
             * return if the connexion is established or not
            */
            {
                bool connexion = false;
                ushort transmissionMode = 0;
    
                // return 1:passive->active   2:active->passive   3:passive   4:active    others:error;
                transmissionMode = FtpTransmissionMode();
    
                if (transmissionMode == 1)
                {
                    ftpExport.passive = true;
                    connexion = FtpSwitchConnectionEstablishment(ref ftpExport);
                }
                else if (transmissionMode == 2)
                {
                    ftpExport.passive = false;
                    connexion = FtpSimpleConnectionEstablishment(ref ftpExport);
                }
                else if (transmissionMode == 3)
                {
                    ftpExport.passive = true;
                    connexion = FtpSimpleConnectionEstablishment(ref ftpExport);
                }
                else if (transmissionMode == 4)
                {
                    ftpExport.passive = false;
                    connexion = FtpSimpleConnectionEstablishment(ref ftpExport);
                }
                else
                {
                    ftpExport.message2 = "Erreur de connexion : impossible de déterminer le mode de transmission";
                    ftpExport.errorConnexion = true;
                    connexion = false;
                }
    
                return connexion;
            }
    
            private ushort FtpTransmissionMode()
            /*
             * In function of radio button on the SettingDialog page FTP,
             * get the transmission mode
             * return 0 if error
            */
            {
                /* Simule radio Button */
                bool settingDefaultTransmissionPA = TroboAki.Properties.Settings.Default.FtpDefaultTransfert;
                bool settingDefaultTransmissionAP = TroboAki.Properties.Settings.Default.FtpActifPassifTransfert;
                bool settingDefaultTransmissionP = TroboAki.Properties.Settings.Default.FtpPassifTransfert;
                bool settingDefaultTransmissionA = TroboAki.Properties.Settings.Default.FtpActifTransfert;
                /* ------------------- */
    
                ushort transmissionMode = 0;
    
                if (settingDefaultTransmissionPA)
                {
                    transmissionMode = 1;
                }
                else if (settingDefaultTransmissionAP)
                {
                    transmissionMode = 2;
                }
                else if (settingDefaultTransmissionP)
                {
                    transmissionMode = 3;
                }
                else if (settingDefaultTransmissionA)
                {
                    transmissionMode = 4;
                }
                else
                {
                    transmissionMode = 0;
                }
    
                return transmissionMode;
            }
    
            private bool FtpSimpleConnectionEstablishment(ref FtpExport ftpExport)
            /*
             * Function allowing connexion on the FTP server with FtpWebRequest class,
             * initialize the connexion ang get the method of transmission ( uploadFile, DeleteFile ...)
             * Check connexion and return if the connection was established or not.
            */
            {
                bool connectionEstablished = false;
    
                // Get a new FtpWebRequest
                try
                {
                    ftpExport.request = (FtpWebRequest)FtpWebRequest.Create(ftpExport.serverUri + ftpExport.filesName[ftpExport.cptFileName-1]);
                }
                catch (Exception ex)
                {
                    ftpExport.message1 = "Impossible de se connecter au serveur FTP : \n" + ex.Message;
                    ftpExport.errorSimpleConnectionEstablishment = true;
                    return false;
                }
    
                // Setup object configuration
                ftpExport.request.Credentials = new NetworkCredential(ftpExport.login, ftpExport.password);
                ftpExport.request.UseBinary = true;
                ftpExport.request.KeepAlive = false;
                ftpExport.request.UsePassive = ftpExport.passive;
    
                // Get method
                if (!FtpMethod(ref ftpExport))
                {
                    return false;
                }
    
                try
                {
                    if (ftpExport.method == "UploadFile")
                    {
                        ftpExport.reqStream = ftpExport.request.GetRequestStream();
                        connectionEstablished = true;
                    }
                    else
                    {
                        connectionEstablished = true;
                    }
                }
                catch (Exception ex)
                {
                    ftpExport.message1 = "Impossible de se connecter au serveur FTP: \n" + ex.Message;
                    ftpExport.errorSimpleConnectionEstablishment = true;
                    return false;
                }
    
                return connectionEstablished;
            }
    
            private bool FtpSwitchConnectionEstablishment(ref FtpExport ftpExport)
            /*
             * Function allowing connexion on the FTP server with FtpWebRequest class,
             * initialize the connexion ang get the method of transmission ( uploadFile, DeleteFile ...)
             * Check connexion and return if the connection was established or not.
             * If the connection is false on the first mode, the function switch automaticaly
             * in the other mode (passive->active or active->passive)
            */
            {
                bool connectionEstablished = false;
                bool exception = false;
    
            begin:
                // Get a new FtpWebRequest
                try
                {
                    ftpExport.request = (FtpWebRequest)FtpWebRequest.Create(ftpExport.serverUri + ftpExport.filesName[ftpExport.cptFileName - 1]);
                }
                catch (Exception ex)
                {
                    ftpExport.message1 = "Impossible de se connecter au serveur FTP : \n" + ex.Message;
                    ftpExport.errorFtpSwitchConnectionEstablishment = true;
                    return false;
                }
    
                // Setup object configuration
                ftpExport.request.Credentials = new NetworkCredential(ftpExport.login.Normalize(), ftpExport.password.Normalize());
                ftpExport.request.UseBinary = true;
                ftpExport.request.KeepAlive = false;
                ftpExport.request.UsePassive = ftpExport.passive;
                // Get method
                if (!FtpMethod(ref ftpExport))
                {
                    return false;
                }
    
                try
                {
                    if (ftpExport.method == "UploadFile")
                    {
                        ftpExport.reqStream = ftpExport.request.GetRequestStream();
                        connectionEstablished = true;
                    }
                    else
                    {
                        connectionEstablished = true;
                    }
                }
                catch (Exception ex)
                {
                    if (!exception)
                    {
                        exception = true;
                        ftpExport.passive = !ftpExport.passive;
                        goto begin;
                    }
                    else
                    {
                        ftpExport.message1 = "Impossible de se connecter au serveur FTP : \n" + ex.Message;
                        ftpExport.errorFtpSwitchConnectionEstablishment = true;
                        return false;
                    }
                }
    
                return connectionEstablished;
            }
    
            private bool FtpMethod(ref FtpExport ftpExport)
            /*
             * Get the method of transmission UploadFile or DeleteFile
             * return if the method could be identified in
            */
            {
                if (ftpExport.method == "UploadFile")
                {
                    ftpExport.request.Method = WebRequestMethods.Ftp.UploadFile;
                    return true;
                }
                else if (ftpExport.method == "DeleteFile")
                {
                    ftpExport.request.Method = WebRequestMethods.Ftp.DeleteFile;
                    return true;
                }
                else
                {
                    ftpExport.errorFtpMethod = true;
                    return false;
                }
            }
    
            private bool FtpUpload(ref FtpExport ftpExport, BackgroundWorker worker, DoWorkEventArgs e)
            /*
             * uploading or resuming file
             * The file is open in reading, Two stream are created to read file and write in the request,
             * the file is stocked by block of 4096 bytes in a buffer and sending
            */
            {
                bool upload = false;
    
                string fileName = ftpExport.fileNameUploading;
    
                // Setup variables used to read the uploading file
                try
                {
                    ftpExport.stream = File.OpenRead(ftpExport.path + ftpExport.filesName[ftpExport.cptFileName - 1]);
                }
                catch (Exception ex)
                {
                    ftpExport.errorFtpUpload = true;
                    ftpExport.message1 = "Erreur lors du téléchargement du fichier " + fileName + " sur le serveur : \n" + ex.Message;
                    return false;
                }
    
                int lengthBuffer = 4096;
                long StreamLength = ftpExport.stream.Length;
                byte[] buffer = new byte[lengthBuffer];
                int bytesReads = 0;
    
                ulong percent;
                ulong lengthFilesTotal = ftpExport.lengthFilesTotal;
    
                FileStream tempStream = ftpExport.stream;
                Stream tempReqStream = ftpExport.reqStream;
    
                // Beginning upload file
    
                statusDisplay("Fichier " + fileName + " en cours de téléchargement", "");
    
                do
                {
                    if (worker.CancellationPending == true)
                    {
                        ftpExport.message1 = "Opération annulée";
                        ftpExport.message2 = "";
    
                        // Close all
                        ftpExport.request.Abort();
                        ftpExport.stream.Close();
                        ftpExport.reqStream.Close();
    
                        ftpExport.cancel = true;
                        return false;
                    }
                    try
                    {
                        bytesReads = tempStream.Read(buffer, 0, lengthBuffer);
                        tempReqStream.Write(buffer, 0, bytesReads);
                    }
                    catch (Exception ex)
                    {
                        ftpExport.errorFtpUpload = true;
                        uploadValue = exportedValue;
    
                        // Close all
                        ftpExport.request.Abort();
                        ftpExport.stream.Close();
                        ftpExport.reqStream.Close();
    
                        ftpExport.message1 = "Erreur lors du téléchargement du fichier " + ftpExport.filesName + " sur le serveur : \n" + ex.Message;
                        return false;
                    }
    
                    uploadValue += (ulong)bytesReads;
                    percent = (ulong)(((double)(uploadValue) * 100) / (double)(lengthFilesTotal));
                    worker.ReportProgress((int)percent);
    
                } while (bytesReads != 0);
    
                // Save the currents values when we have more one file exported
                exportedValue += (ulong)ftpExport.stream.Length;
                uploadValue = exportedValue;
    
                // Close Stream
                ftpExport.stream.Close();
    
                // Close ReqStream
                ftpExport.reqStream.Close();
    
                upload = true;
    
                return upload;
            }
    
            private bool FtpDeleteFiles(ref FtpExport ftpExport)
            /*
             * Function for removing file on the server
             * Is called when user cancel uploading
            */
            {
                bool connexion = false;
    
                ftpExport.method ="DeleteFile";
    
                connexion = FtpConnexion(ref ftpExport);
    
                do
                {
                    connexion = FtpConnexion(ref ftpExport);
                    try
                    {
                        FtpWebResponse fileDeleted = (FtpWebResponse)ftpExport.request.GetResponse();
                    }
                    catch (Exception ex)
                    {
                        ftpExport.message1 = " Impossible de supprimer le fichier " + ftpExport.filesName[ftpExport.cptFileName] + " : \n" + ex.Message;
                        ftpExport.errorFtpDeleteFiles = true;
                        return false;
                    }
                        
                    // decrease to delete the next file exported
                    ftpExport.cptFileName--;
    
                } while (ftpExport.cptFileName > 0);
    
                return true;
    
            }
            #endregion
        }
    }

    Sorry i posted full code but i think its important to post all.
    Coz i am not getting where is the problem.

    Thank you for you help

    Tuesday, August 13, 2013 8:58 AM

All replies

  • Note: My file is zip file is this a problem..?

    Tuesday, August 13, 2013 9:18 AM
  • Hi NK sharma,

      Welcome to MSDN Forum Support.

      The RFC for FTP states that any 5XX messages are indeed server issued.  This is a server telling you that according to it, you are not logged in to do this particular function.

    Here's what I'd try, attempt to do a FTP using a FTP Client and make sure that you can get it to work with that particular client.  Then... download Wireshark and start a trace of this "working scenario".  From there, rerun the trace using the failing scenario and compare the difference.  You will at least be able to go to the server folks on the other side and give them specific information about what is different. 

    If you don't run the traces then all you can tell them is this based on the analysis of your code.  "I am seeing a 530 error when I am sending the credentials "userid" and "password" to your system."  You could ask them "What rights does the userid of "userid" have on your server.  BTW using a userid of "userid" is not too smart... You may want to tell them that. 

      Here is a thread is similiar to your thread, you can refer to it.

      The remote server returned an error: (530) Not logged in.

    Jason Wang
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    Wednesday, August 14, 2013 4:35 AM
    Moderator