private static void DeleteFolderFiles(string server, string username, string password, string folder)
        {
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + server + folder);

            request.Credentials = new NetworkCredential(username, password);
            request.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
            request.KeepAlive   = false;


            WebResponse   resp        = request.GetResponse();
            StreamReader  str         = new StreamReader(resp.GetResponseStream());
            List <string> tobedeleted = new List <string>();
            string        line;

            do
            {
                line = str.ReadLine();

                if ((line != null) && (!line.StartsWith("d")))
                {
                    string pathname = Regex.Match(line, @".*?\s\d{2}:\d{2}\s(.+)$").Groups[1].Value;
                    tobedeleted.Add(folder + pathname);
                }
            }while (!string.IsNullOrEmpty(line));
            str.Close();
            resp.Close();

            foreach (string file in tobedeleted)
            {
                FtpCommands.SendCommand(server, username, password, "DELE " + file, (tobedeleted[tobedeleted.Count - 1] != file));
            }
        }
        public static void DeleteFolder(string server, string username, string password, string folder)
        {
            folder = FixFtpFolderPrefix(server, username, password, folder);

            //check first of folder there
            if (IsFtpFolderCorrect(server, username, password, folder))
            {
                List <string> foundItems = new List <string>();

                try
                {
                    GetSubFolders(server, username, password, folder, foundItems);
                }
                catch { }

                foreach (string path in foundItems)
                {
                    DeleteFolderFiles(server, username, password, path);
                }


                //sort by number of slahes!
                for (int current = 0; current < foundItems.Count - 1; current++)
                {
                    int biggest = current;
                    for (int check = current + 1; check < foundItems.Count; check++)
                    {
                        if (foundItems[biggest].Split('/').Length < foundItems[check].Split('/').Length)
                        {
                            biggest = check;
                        }
                    }

                    if (biggest != current)
                    {
                        string temp = foundItems[current];
                        foundItems[current] = foundItems[biggest];
                        foundItems[biggest] = temp;
                    }
                }



                foreach (string path in foundItems)
                {
                    RemoveFolder(server, username, password, path);
                }


                //now delete the root folder!
                try
                {
                    FtpCommands.DeleteFolderFiles(server, username, password, folder);
                }
                catch { }

                FtpCommands.SendCommand(server, username, password, "RMD " + folder, false);
            }
        }
Пример #3
0
        public static string StartScript(string server, string script)
        {
            FtpCommands.SetExecutePermissions(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, script.Split('?')[0], false);

            HardwareDetails det      = HardwareDetailsFactory.CreateDetails((HardwareTypeEnum)Enum.Parse(typeof(HardwareTypeEnum), Settings.Default.HardwareType));
            string          resquest = string.Empty;
            var             port     = 0;

            if (det.RepositoryType == "z")
            {
                script    = "/share/" + script;
                script    = Regex.Replace(script, @"\?", " ");
                resquest  = Regex.Replace(script, @"\&", " ");
                resquest += "\n";
                port      = 23;
            }
            else
            {
                resquest += "GET " + ((Settings.Default.WebserverSubFolder.Length > 0) ? "/" + Settings.Default.WebserverSubFolder + "/" : "/") + script + " HTTP/1.1" + "\r\n";
                resquest += "Host: localhost.drives:8883" + "\r\n";
                resquest += "\r\n";
                port      = 8883;
            }


            TcpClient clnt = new TcpClient();

            clnt.Connect(server, port);

            ASCIIEncoding ascend = new ASCIIEncoding();

            byte[] send = ascend.GetBytes(resquest);
            clnt.GetStream().Write(send, 0, send.Length);
            clnt.GetStream().Flush();

            string response = string.Empty;

            byte[] readbuffer = new byte[1024];
            int    readbytes  = 0;

            //clnt.GetStream().ReadTimeout = 30000;
            do
            {
                readbytes = 0;
                try
                {
                    readbytes = clnt.GetStream().Read(readbuffer, 0, readbuffer.Length);
                    response += ascend.GetString(readbuffer, 0, readbytes);
                }
                catch (IOException)
                {
                }


                Thread.Sleep(100);
            }while ((readbytes != 0) && (!response.ToLower().Contains("</html>") && (!response.ToLower().Contains(new string(new char[] { (char)4 })))));
            return(response);
        }
        public static bool DeleteFile(string server, string username, string password, string remoteFile)
        {
            remoteFile = FixFtpFolderPrefix(server, username, password, remoteFile);

            try
            {
                FtpCommands.SendCommand(server, username, password, "DELE " + remoteFile, false);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        private static void RemoveFolder(string server, string username, string password, string folder)
        {
            //FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + server + folder);
            //request.Credentials = new NetworkCredential(username,password);
            //request.Method = WebRequestMethods.Ftp.RemoveDirectory;

            //try
            //{
            //    request.GetResponse().Close();
            //}
            //catch (WebException)
            //{
            //}
            FtpCommands.SendCommand(server, username, password, "RMD " + folder, false);
        }
        private void InstallThread()
        {
            try
            {
                string installResult = string.Empty;

                //DELETE FILES BEFORE INSTALL
                foreach (string deleteFile in DeleteFilesBeforeInstall)
                {
                    FtpCommands.DeleteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, deleteFile);
                }

                //DELETE FOLDERS BEFORE INSTALL
                foreach (string deleteFolder in DeleteFoldersBeforeInstall)
                {
                    FtpCommands.DeleteFolder(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, deleteFolder);
                }

                //UPLOAD CONTENT
                FtpCommands.UploadFolder(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, LocalFolder, UploadLocation, OnProgressChanged);


                //MOVE FILES TO ROOT WHEN REQUIRED
                if ((InstallItem is RepositoryCustomMenuInfo) && (UploadLocation != "/"))
                {
                    FtpCommands.RenameRemoteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, UploadLocation + "index.htm", "/index.htm", true);
                }
                if (((InstallItem is RepositoryApplicationInfo) || (InstallItem is RepositoryWaitImagesInfo)) && (UploadLocation != "/"))
                {
                    FtpCommands.RenameRemoteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, UploadLocation + Settings.Default.InstallPrepareScriptURL.Substring(Settings.Default.InstallPrepareScriptURL.LastIndexOf("/") + 1), "/" + Settings.Default.InstallPrepareScriptURL.Substring(Settings.Default.InstallPrepareScriptURL.LastIndexOf("/") + 1), true);
                }

                //during installation of an application the appinit should be moved to the root of the HDD
                //when target dir it not the root
                if ((InstallItem is RepositoryApplicationInfo) && (UploadLocation != "/"))
                {
                    FtpCommands.RenameRemoteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, "RNFR " + UploadLocation + Settings.Default.AppInitScriptURL.Substring(Settings.Default.AppInitScriptURL.LastIndexOf("/") + 1), "/" + Settings.Default.AppInitScriptURL.Substring(Settings.Default.AppInitScriptURL.LastIndexOf("/") + 1), true);
                }

                //EXECUTE SCRIPTS
                OnProgressChanged(-1, Resources.Text_Installing + " " + InstallItem.Name);
                foreach (string script in ExecuteScriptSequence)
                {
                    //execute start scripts but do not log the output of installing appinit.cgi
                    if (script == Settings.Default.AppInitScriptURL.Substring(Settings.Default.AppInitScriptURL.LastIndexOf('/') + 1))
                    {
                        HttpCommands.StartScript(Settings.Default.Server, script);
                    }
                    else
                    {
                        installResult += HttpCommands.StartScript(Settings.Default.Server, script);
                    }
                }

                //CLEANUP AFTER INSTALL
                if (CleanupAfterInstall)
                {
                    if (Directory.Exists(LocalFolder))
                    {
                        FtpCommands.CleanupFolder(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, LocalFolder, UploadLocation);
                    }
                }
                if ((InstallItem is RepositoryApplicationInfo) || (InstallItem is RepositoryWaitImagesInfo))
                {
                    FtpCommands.DeleteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, Settings.Default.InstallPrepareScriptURL.Substring(Settings.Default.InstallPrepareScriptURL.LastIndexOf("/") + 1));
                }
                if (InstallItem is RepositoryApplicationInfo)
                {
                    FtpCommands.DeleteFile(Settings.Default.Server, Settings.Default.Username, Settings.Default.Password, Settings.Default.AppInitScriptURL.Substring(Settings.Default.AppInitScriptURL.LastIndexOf("/") + 1));
                }

                FtpCommands.CloseCachedConnection();
                OnProgressChanged(100, string.Empty);

                OnInstallationFinished(true, installResult);
            }
            catch (Exception ex)
            {
                Logger.GetInstance().AddLogLine(LogLevel.Error, "WebException during install method of UploadInstaller", ex);
                MessageBox.Show(Resources.MessageBox_InstallActionFailed, Resources.MessageBox_InstallationActionCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                OnInstallationFinished(false, InstallResult);
            }
        }
 public static void SetExecutePermissions(string server, string username, string password, string filename, bool keepOpen)
 {
     filename = FixFtpFolderPrefix(server, username, password, filename);
     FtpCommands.SendCommand(server, username, password, "SITE chmod 777 " + filename, false);
 }
        public static bool CleanupFolder(string server, string username, string password, string localFolder, string remoteFolder)
        {
            remoteFolder = FixFtpFolderPrefix(server, username, password, remoteFolder);

            List <string> files = new List <string>();

            files.AddRange(Directory.GetFiles(localFolder, "*.*", SearchOption.AllDirectories));

            int c = 0;

            while (c < files.Count)
            {
                if (files[c].Contains("\\.svn\\"))
                {
                    files.RemoveAt(c);
                }
                else
                {
                    c++;
                }
            }


            List <string> deleteFolders = new List <string>();

            foreach (string file in files)
            {
                string relativeRemotePath = "/";
                if (file.Length > localFolder.Length)
                {
                    relativeRemotePath = file.Substring(localFolder.Length + 1, (file.Length - (localFolder.Length + 1)));
                }


                relativeRemotePath = remoteFolder + relativeRemotePath.Replace('\\', '/');
                relativeRemotePath = relativeRemotePath.Substring(0, relativeRemotePath.LastIndexOf('/') + 1);


                FtpWebRequest upload = (FtpWebRequest)FtpWebRequest.Create("ftp://" + server + relativeRemotePath + Path.GetFileName(file));
                upload.Credentials = new NetworkCredential(username, password);
                upload.UsePassive  = true;
                upload.UseBinary   = true;
                upload.KeepAlive   = false;

                upload.Method = WebRequestMethods.Ftp.DeleteFile;

                try
                {
                    upload.GetResponse().Close();
                }
                catch (WebException)
                {
                    //don't matter if file can't be deleted
                }

                //paranoide? I think so ;-)
                if (relativeRemotePath != "/")
                {
                    if (!deleteFolders.Contains(relativeRemotePath))
                    {
                        deleteFolders.Add(relativeRemotePath);
                    }
                }
            }

            //sort by number of slahes!
            for (int current = 0; current < deleteFolders.Count - 1; current++)
            {
                int biggest = current;
                for (int check = current + 1; check < deleteFolders.Count; check++)
                {
                    if (deleteFolders[biggest].Split('/').Length < deleteFolders[check].Split('/').Length)
                    {
                        biggest = check;
                    }
                }

                if (biggest != current)
                {
                    string temp = deleteFolders[current];
                    deleteFolders[current] = deleteFolders[biggest];
                    deleteFolders[biggest] = temp;
                }
            }

            foreach (string folder in deleteFolders)
            {
                FtpCommands.SendCommand(server, username, password, "RMD " + folder, (deleteFolders[deleteFolders.Count - 1] != folder));
            }


            return(true);
        }
        public static bool UploadFolder(string server, string username, string password, string localFolder, string remoteFolder, Functions.UpdateProgressInfo OnProgressChange)
        {
            remoteFolder = FixFtpFolderPrefix(server, username, password, remoteFolder);

            List <string> createdFTPFolders = new List <string>();
            List <string> files             = new List <string>();

            files.AddRange(Directory.GetFiles(localFolder, "*.*", SearchOption.AllDirectories));
            int totalFileSize = 0;
            int totalUploaded = 0;

            int c = 0;

            while (c < files.Count)
            {
                if (files[c].Contains("\\.svn\\"))
                {
                    files.RemoveAt(c);
                }
                else
                if ((!files[c].EndsWith(Path.DirectorySeparatorChar + ".config")) && (Regex.Match(files[c], @"\\\.[^\\]*$").Success))
                {
                    files.RemoveAt(c);
                }
                else
                if (files[c].EndsWith("\\Thumbs.db"))
                {
                    files.RemoveAt(c);
                }
                else
                {
                    totalFileSize += (int)new FileInfo(files[c]).Length;
                    c++;
                }
            }


            foreach (string file in files)
            {
                string relativeRemotePath = "/";
                if (file.Length > localFolder.Length)
                {
                    relativeRemotePath = file.Substring(localFolder.Length, (file.Length - localFolder.Length));
                }


                relativeRemotePath = remoteFolder + relativeRemotePath.Replace('\\', '/');
                relativeRemotePath = relativeRemotePath.Substring(0, relativeRemotePath.LastIndexOf('/') + 1);


                //create all folders
                string[] paths  = relativeRemotePath.Substring(1).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                string   create = string.Empty;
                for (int i = 0; i < paths.Length; i++)
                {
                    create += paths[i] + "/";

                    if (!createdFTPFolders.Contains(create))
                    {
                        FtpCommands.SendCommand(server, username, password, "MKD " + create, i < (paths.Length - 1));
                        createdFTPFolders.Add(create);
                    }
                }

                FtpWebRequest upload = null;
                Stream        str    = null;

                //work around for the 503 when the parent folder was deleted just before uploading again
                bool done    = false;
                int  Retries = Settings.Default.FileUploadRetries553;
                while (!done)
                {
                    try
                    {
                        upload             = (FtpWebRequest)FtpWebRequest.Create("ftp://" + server + relativeRemotePath + Path.GetFileName(file));
                        upload.Credentials = new NetworkCredential(username, password);
                        upload.UsePassive  = true;
                        upload.UseBinary   = true;
                        upload.KeepAlive   = false;

                        upload.Method = WebRequestMethods.Ftp.UploadFile;
                        str           = upload.GetRequestStream();
                        done          = true;
                    }
                    catch (WebException ex)
                    {
                        try
                        {
                            str.Close();
                        }
                        catch { }

                        if ((!ex.Message.Contains("553")) || (Retries == 0))
                        {
                            throw ex;
                        }
                        else
                        {
                            Retries--;
                            Thread.Sleep(1000);
                        }
                    }
                }

                byte[]     uploaddata = new byte[10240];
                FileStream uploadFile = File.OpenRead(file);
                int        PrevValue  = -1;

                while (uploadFile.Position < uploadFile.Length)
                {
                    int read = uploadFile.Read(uploaddata, 0, uploaddata.Length);
                    totalUploaded += read;

                    str.Write(uploaddata, 0, read);

                    if (OnProgressChange != null)
                    {
                        int Procent = (int)((totalUploaded / (float)totalFileSize) * 100);
                        if (PrevValue != Procent)
                        {
                            OnProgressChange(Procent, "Uploading files");
                            PrevValue = Procent;
                        }
                    }
                }

                str.Close();
                uploadFile.Close();
                upload.GetResponse().Close();
            }

            return(true);
        }