DeleteDirectory() public static method

public static DeleteDirectory ( string directoryPath ) : void
directoryPath string
return void
示例#1
0
        private void RemoveBinRecursiveFrom(string directories)
        {
            var subdirectoriesAsArray = System.IO.Directory.GetDirectories(directories);

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

            bool wasAnythingDeleted = false;

            foreach (var directory in subdirectoriesAsArray)
            {
                string strippedSubDirectory = FileManager.RemovePath(directory);

                if (strippedSubDirectory.ToLowerInvariant() == "bin" ||
                    strippedSubDirectory.ToLowerInvariant() == "obj")
                {
                    // Use FileManager to delete the directory - It will do it recursively:
                    //System.IO.Directory.Delete(directory);
                    FileManager.DeleteDirectory(directory);
                    wasAnythingDeleted = true;
                }
                else
                {
                    directoriesToProcess.Add(directory);
                }
            }

            // let's go deeper if we haven't found bin/obj yet
            if (!wasAnythingDeleted)
            {
                foreach (var directory in directoriesToProcess)
                {
                    RemoveBinRecursiveFrom(directory);
                }
            }
        }
示例#2
0
        private async void OnDeleteAllImagesExecute()
        {
            var result = MessageDialogService.ShowOKCancelDialog("Удаление информации об изображениях.",
                                                                 "Удалять информацию по сем картинкам в даном расположении?");

            if (result == MessageDialogResult.OK)
            {
                var          cnf      = new ConfigurationData();
                var          lg       = new Logger();
                var          fm       = new FileManager(cnf, lg);
                IDataManager dm       = new DataManager(cnf, fm, lg, 0);
                var          dmResult = dm.RemoveImagesFromDrive(this.Id);
                if (dmResult.Success)
                {
                    var path = Path.Combine(cnf.GetTargetImagePath(), string.Format("drive{0}", Id));
                    fm.DeleteDirectory(path);
                }
                await LoadAsync(Id);

                await MessageDialogService.ShowInfoDialogAsync("Удаление выполнено!");

                //TODO: Удаление из БД
                //TODO: Удаление в файловой системе
            }
        }
示例#3
0
        public IActionResult DeleteProduct(int Id)
        {
            string nvm;

            try
            {
                var entity = dbProductAbstract.FindById(Id);
                if (entity != null)
                {
                    var ProductImageFiles      = _db.ProductImage.Where(x => x.ProductId == entity.Id).ToList();
                    var ProductAbstractDeleted = dbProductAbstract.DeleteById(Id);
                    if (true)
                    {
                        if (ProductImageFiles.Count > 0)
                        {
                            foreach (var item in ProductImageFiles)
                            {
                                //delete related image files:
                                bool imgDel          = FileManager.DeleteFile(contentRootPath, item.ImagePath);
                                bool thumbnailImgDel = FileManager.DeleteFile(contentRootPath, item.ImageThumbnailPath);
                            }
                            bool dirDel = FileManager.DeleteDirectory(contentRootPath, ProductImageFiles.FirstOrDefault().ImagePath);
                        }
                        nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Success_Remove, contentRootPath);
                        return(Json(nvm));
                    }
                }
            }
            catch (Exception)
            {
            }
            nvm = NotificationHandler.SerializeMessage <string>(NotificationHandler.Failed_Remove, contentRootPath);
            return(Json(nvm));
        }
示例#4
0
 public void DeleteDirectory()
 {
     if (SelectedCategory != null && SelectedCategory.Name != "Wormwood")
     {
         if (SelectedCategory.FileCount == 0)
         {
             FM.DeleteDirectory(SelectedCategory.FullName);
             Categories.Remove(SelectedCategory);
             RefreshCategories();
             ChangeCategory();
         }
         else
         {
             DialogResult confirm = MessageBox.Show("This category contains files, do you want to delete all files in this category?", "Confirm", MessageBoxButtons.YesNo);
             if (confirm == DialogResult.Yes)
             {
                 foreach (FileModel file in FM.GetFiles(SelectedCategory.FullName))
                 {
                     FM.DeleteFile(file.FullName);
                 }
                 SelectedCategory.FileCount = 0;
                 DeleteDirectory();
             }
         }
     }
 }
示例#5
0
    public static void Main()
    {
        FileManager newfile = new FileManager();

        // Create a new directory
        newfile.FilePath = @"files/file-folder"; // directory name
        newfile.CreateDirectory();

        // Write file in newly created directory
        newfile.FilePath = @"files/file-folder/another.txt"; // directory and file name
        newfile.CreateAndWriteFile();

        // Read from the newly created file
        newfile.FilePath = @"files/file-folder/another.txt";
        newfile.ReadFromFile();

        // Copy to new directory
        string source      = @"files/file-folder";
        string destination = @"files/another-folder";

        newfile.CopyToAnotherDirectory(source, destination, "another.txt");

        // Delete file
        newfile.FilePath = @"files/file-folder/another.txt";
        newfile.DeleteFile();

        // Delete directory
        newfile.FilePath = @"files/file-folder";
        newfile.DeleteDirectory();
    }
示例#6
0
        /**
         * Physically remove the project from the project folder. The project must be opened
         * on order to delete it. If the user accepts the verification to delete the project
         * the project will be unloaded then all folders and files will be removed. This process
         * does NOT remove any related files from the document library.
         */
        public static void DeleteProject()
        {
            TestProgramSet testSet = Instance.CurrentTestProgramSet;

            if (testSet != null)
            {
                string testSetName = testSet.TestSetName;
                string fullName    = testSet.TestSetDirectory.FullName;
                if (DialogResult.Yes ==
                    MessageBox.Show(
                        string.Format("Are you sure you want to delete Test Set Project \"{0}\"?", testSetName),
                        @"V E R I F Y",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    HourGlass.Start();
                    try
                    {
                        CloseProject();
                        GC.Collect();
                        if (FileManager.DeleteDirectory(fullName, true))
                        {
                            LogManager.Trace("Test Set Project \"{0}\" has been deleted.", testSetName);
                        }
                    }
                    catch (Exception err)
                    {
                        LogManager.Error(err.Message);
                    }
                    finally
                    {
                        HourGlass.Stop();
                    }
                }
            }
        }
示例#7
0
        private void btnGenrate_Click(object sender, EventArgs e)
        {
            try
            {
                string RootlibraryPath = USUtil.SavePath;
                FileManager.DeleteDirectory(RootlibraryPath);

                string defaultNameSpace = tbxDefaultNamespace.Text.Trim();
                if (defaultNameSpace == string.Empty)
                {
                    defaultNameSpace = USUtil.DefaultNameSpace;
                }

                if (ddlType.SelectedValue.ToString().Trim() == USUtil.Tbl || ddlType.SelectedValue.ToString().Trim() == string.Empty)
                {
                    AdonaiBuildStructureInfo buildInfo = new AdonaiBuildStructureInfo();
                    buildInfo.TableName            = txtTableName.Text.Trim();
                    buildInfo.InfoClassName        = txtClassName.Text.Trim();
                    buildInfo.ConnectionString     = ConnectionString;
                    buildInfo.IsNullableRequired   = chkIsNullableRequred.Checked;
                    buildInfo.IsSerializable       = chklsSerializable.Checked;
                    buildInfo.IsControllerRequired = chkIsController.Checked;
                    buildInfo.IsProviderRequired   = chkIsProviderRequred.Checked;
                    buildInfo.InfoNameSpace        = defaultNameSpace;
                    BELLBuilderController ctlBELL = new BELLBuilderController();
                    string output = ctlBELL.GetTableInfoByTableNameandClassName(buildInfo);

                    AddToFastNote(output);
                }
                else
                {
                    AppUtilityDataProvider dataProvider = new AppUtilityDataProvider();
                    IList <KeyValuePair <string, object> > inputParamList = dataProvider.GetSpPrametersBySpName(txtTableName.Text.Trim(), ConnectionString);
                    if (inputParamList.Count > 0)
                    {
                        IList <KeyValuePair <string, object> > listColl = new List <KeyValuePair <string, object> >();

                        ArrayList arrColl = BuildSQLParameter(inputParamList);
                        for (int i = 0; i < arrColl.Count; i++)
                        {
                            listColl.Add(new KeyValuePair <string, object>(arrColl[i].ToString(), "1"));
                        }

                        string strInfoText = dataProvider.ExecuteGivenProcedureBuildInfoClass(txtTableName.Text, tbxDefaultNamespace.Text.Trim(), txtClassName.Text.Trim(), listColl, ConnectionString);

                        AddToFastNote(strInfoText);
                    }
                    else
                    {
                        USUtil.DisplayMessage(USUtil.msg_SPHasNoParam, USUtil.msg_ErrorCaption, false);
                    }
                }
            }
            catch (Exception ex)
            {
                USUtil.DisplayMessage(ex.Message, USUtil.msg_ErrorCaption, false);
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            string RootlibraryPath = USUtil.SavePath;

            FileManager.DeleteDirectory(RootlibraryPath);
            GetCheckedItemFromList();
            this.Cursor = Cursors.Arrow;
        }
示例#9
0
        public static void AskAndImportGroup()
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = "Glue Group (*.ggpz)|*.ggpz";

            var dialogResult = dialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                string fileName = dialog.FileName;

                // First let's unzip the file:
                string unpackDirectory = FileManager.UserApplicationDataForThisApplication + "GroupUnzip\\";

                if (Directory.Exists(unpackDirectory))
                {
                    FileManager.DeleteDirectory(unpackDirectory);
                }
                Directory.CreateDirectory(unpackDirectory);

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

                using (ZipFile zip1 = ZipFile.Read(fileName))
                {
                    foreach (ZipEntry zipEntry in zip1)
                    {
                        string directory = FileManager.GetDirectory(zipEntry.FileName, RelativeType.Relative);

                        zipEntry.Extract(unpackDirectory, true);

                        foundFiles.Add(unpackDirectory + zipEntry.FileName);
                    }
                }

                // Now that all files have been unzipped let's loop through them and
                // import them
                foreach (string zipFile in foundFiles)
                {
                    string relativeToUnzipRoot = FileManager.MakeRelative(zipFile, unpackDirectory);

                    if (relativeToUnzipRoot.ToLower().StartsWith("entities/"))
                    {
                        relativeToUnzipRoot = relativeToUnzipRoot.Substring("entities/".Length);
                    }
                    else if (relativeToUnzipRoot.ToLower().StartsWith("screens/"))
                    {
                        relativeToUnzipRoot = relativeToUnzipRoot.Substring("screens/".Length);
                    }

                    // remove the file name (like Entity.entz) to get the directory
                    string directory = FileManager.GetDirectory(relativeToUnzipRoot, RelativeType.Relative);

                    ImportElementFromFile(zipFile, false, directory);
                }
            }
        }
示例#10
0
        private static void CopyContentsUpOneDirectory(string unpackDirectory)
        {
            var directories = Directory.GetDirectories(unpackDirectory);

            var directoryToMove = directories.First();

            FileManager.CopyDirectory(directoryToMove, unpackDirectory, false);

            FileManager.DeleteDirectory(directoryToMove);
        }
示例#11
0
    private void DeployLauncher()
    {
        try
        {
            // Cache current build target
            EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Caching current build target...", 0);
            BuildTarget      cachedTarget      = EditorUserBuildSettings.activeBuildTarget;
            BuildTargetGroup cachedTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;

            // Delete previous generated archive
            if (FileManager.DirectoryExists(Path.Combine(SettingsManager.DEPLOY_PATH, "Launcher")))
            {
                FileManager.DeleteDirectory(Path.Combine(SettingsManager.DEPLOY_PATH, "Launcher"));
            }

            // Build selected Launcher scene
            BuildTarget      target      = (BuildTarget)Enum.Parse(typeof(BuildTarget), _platformsAvailable[_platformToDeployDropdownIndex]);
            BuildTargetGroup targetGroup = BuildTargetGroup.Standalone;
            EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, target);
            BuildPipeline.BuildPlayer(new string[] { _scenesInBuildSettings[_launcherSceneToDeployDropdownIndex] },
                                      SettingsManager.DEPLOY_PATH + "Launcher" + Path.DirectorySeparatorChar + _launcherCustomName + GetAppExtension(target),
                                      target, BuildOptions.None);

            FileManager.DeleteFiles(Path.Combine(SettingsManager.DEPLOY_PATH, "Launcher"), "*.pdb");

            // ZIP generated application
            EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Compressing deployed build...", 0.5f);
            MHLab.PATCH.Compression.CompressionType ctype = MHLab.PATCH.Compression.CompressionType.ZIP;

            // Delete previous generated archive
            if (FileManager.FileExists(Path.Combine(SettingsManager.DEPLOY_PATH, "patcher.zip")))
            {
                FileManager.DeleteFile(Path.Combine(SettingsManager.DEPLOY_PATH, "patcher.zip"));
            }

            m_patchManager.DeployCompress(
                Path.Combine(SettingsManager.DEPLOY_PATH, "Launcher"),
                Path.Combine(SettingsManager.DEPLOY_PATH, "patcher.zip"),
                ctype
                );

            // Clean up useless files
            EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Cleaning up...", 0.9f);
            Path.Combine(SettingsManager.DEPLOY_PATH, "Launcher");

            // Restore original build target
            EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Finalization...", 1f);
            EditorUserBuildSettings.SwitchActiveBuildTarget(cachedTargetGroup, cachedTarget);
            EditorUtility.ClearProgressBar();
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
 static void ClearTempFile()
 {
     if (FileManager.IsDirectoryExist(LuaConst.luaTempDir))
     {
         FileManager.DeleteDirectory(LuaConst.luaTempDir);
     }
     if (FileManager.IsDirectoryExist(ConfigConst.tempconfigDir))
     {
         FileManager.DeleteDirectory(ConfigConst.tempconfigDir);
     }
 }
示例#13
0
 public void DeleteFontCacheFolder()
 {
     try
     {
         FileManager.DeleteDirectory(AbsoluteFontCacheFolder);
     }
     catch (Exception e)
     {
         System.Windows.Forms.MessageBox.Show("Error deleting font cache:\n" + e.ToString());
     }
 }
        public override void Handle(string[] args)
        {
            var toDelete = args[0];

            if (_fileManager.StringPathIsDirectory(toDelete))
            {
                _fileManager.DeleteDirectory(toDelete);
                return;
            }

            _fileManager.DeleteFile(toDelete);
        }
示例#15
0
文件: Program.cs 项目: oswaldor/Plume
        /// <summary>
        /// Copy model files from current model repository to remote model repository (file share).
        /// </summary>
        private static void CopyModels(object needDeleteModel)
        {
            bool needDeleteFromLocal;

            if (!bool.TryParse(needDeleteModel.ToString(), out needDeleteFromLocal))
            {
                throw new Exception("Invalid value for boolean flag\"needDeleteModel\".");
            }

            string currentConfigFileForTest = "";

            while (IsRunning())
            {
                string configFileForTest;

                if (configFileQueue.TryPeek(out configFileForTest))
                {
                    // Make sure model files are ready.
                    while (!LDAModelStatusChecker.AreModelFilesReady(configFileForTest))
                    {
                        Thread.Sleep(5);
                        if (configFileForTest != currentConfigFileForTest)
                        {
                            StatusMessage.Write("Waiting for model under\r\n\t" + Path.GetDirectoryName(configFileForTest));
                            currentConfigFileForTest = configFileForTest;
                        }
                    }

                    if (configFileQueue.TryDequeue(out configFileForTest))
                    {
                        string sourceDir = Path.GetDirectoryName(configFileForTest);

                        string destinationDir = GetDestinationPathFromSourcePath(sourceDir, RemoteModelRepositoryPath);

                        StatusMessage.Write(string.Format("Copying model under\r\n\t{0}-->{1}", sourceDir, RemoteModelRepositoryPath), ConsoleColor.DarkGreen);
                        string message = FileManager.CopyDirectoryOrFile(sourceDir, destinationDir);
                        StatusMessage.Write(message, ConsoleColor.Green);
                        int retVal = int.Parse(message.Split('\t')[0]);

                        if (retVal == 0 && needDeleteFromLocal)
                        {
                            StatusMessage.Write(string.Format("Deleting directory\r\n\t{0}", sourceDir), ConsoleColor.DarkGreen);
                            ConsoleColor color;
                            message = FileManager.DeleteDirectory(sourceDir, out color);
                            StatusMessage.Write(message, color);
                        }
                    }
                }
            }

            // Tell main thread that all models listed in the queue have been copied.
            Interlocked.Decrement(ref flag);
        }
示例#16
0
 static public int DeleteDirectory_s(IntPtr l)
 {
     try {
         System.String a1;
         checkType(l, 1, out a1);
         FileManager.DeleteDirectory(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
示例#17
0
    protected async Task RestoreStoppedDownloadAsync()
    {
        // Restore and clean up failed download
        try
        {
            // Delete the downloaded processed files
            foreach (FileSystemPath path in ProcessedPaths)
            {
                try
                {
                    if (path.FileExists)
                    {
                        FileManager.DeleteFile(path);
                    }
                    else if (path.DirectoryExists)
                    {
                        FileManager.DeleteDirectory(path);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Deleting processed file from incomplete download operation");
                }
            }

            // Restore backed up files
            foreach (FileSystemPath item in Directory.EnumerateFiles(LocalTempDir.TempPath, "*", SearchOption.AllDirectories))
            {
                // Get the path to move to
                FileSystemPath file = OutputDirectory + (item - LocalTempDir.TempPath);

                try
                {
                    // Move back the file
                    FileManager.MoveFile(item, file, true);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Restoring backed up file from incomplete download operation");
                }
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "Cleaning up incomplete download operation");

            // Let the user know the restore failed
            await Services.MessageUI.DisplayExceptionMessageAsync(ex, String.Format(Resources.Download_RestoreStoppedDownloadError, LocalTempDir.TempPath, ServerTempDir.TempPath));
        }
    }
示例#18
0
    public static bool ClearDirectory(string fullPath, string[] fileExtensionFilter, string[] folderFilter)
    {
        bool result;

        try
        {
            if (fileExtensionFilter != null)
            {
                string[] files = Directory.GetFiles(fullPath);
                for (int i = 0; i < files.Length; i++)
                {
                    if (fileExtensionFilter != null && fileExtensionFilter.Length > 0)
                    {
                        for (int j = 0; j < fileExtensionFilter.Length; j++)
                        {
                            if (files[i].Contains(fileExtensionFilter[j]))
                            {
                                FileManager.DeleteFile(files[i]);
                                break;
                            }
                        }
                    }
                }
            }
            if (folderFilter != null)
            {
                string[] directories = Directory.GetDirectories(fullPath);
                for (int k = 0; k < directories.Length; k++)
                {
                    if (folderFilter != null && folderFilter.Length > 0)
                    {
                        for (int l = 0; l < folderFilter.Length; l++)
                        {
                            if (directories[k].Contains(folderFilter[l]))
                            {
                                FileManager.DeleteDirectory(directories[k]);
                                break;
                            }
                        }
                    }
                }
            }
            result = true;
        }
        catch (Exception)
        {
            result = false;
        }
        return(result);
    }
示例#19
0
 public bool DeletePlayer(Player player)
 {
     if (this.Players.Contains(player))
     {
         FileManager.DeleteDirectory(player.DirectoryPath, true);
         int index = ConfigManager.Current.GameConfig.PlayersConfigPath.IndexOf(player.ConfigFilePath);
         if (index >= 0 && index < ConfigManager.Current.GameConfig.PlayersConfigPath.Count)
         {
             ConfigManager.Current.GameConfig.PlayersConfigPath.RemoveAt(index);
             ConfigManager.Current.SaveGameConfig();
         }
         return(this.Players.Remove(player));
     }
     return(false);
 }
示例#20
0
    public static void CopyScript()
    {
        FileManager.DeleteDirectory(UpdateManager.UpdateTest + SCRIPT_PATH);
        List <string> fileList = new List <string>();

        GetAllScriptFile(Application.dataPath + "/Resources" + SCRIPT_PATH, fileList);

        for (int i = 0; i < fileList.Count; ++i)
        {
            //TODO:加密每一个script文件,并拷贝到PersistentDataPath
            var file       = fileList[i];
            var targetFile = file.Replace(Application.dataPath + "/Resources", UpdateManager.UpdateTest);
            var content    = FileManager.LoadFileWithString(file);
            FileManager.CreateFileWithString(targetFile, EncryptScript(content));
        }
    }
示例#21
0
        private void HandleUninstallPlugin(object sender, RoutedEventArgs e)
        {
            if (DataContext != null)
            {
                var directoryToDelete = FileManager.GetDirectory(pluginContainer.AssemblyLocation);

                // try deleteing it, probably won't be able to because the plugin is in-use
                try
                {
                    FileManager.DeleteDirectory(directoryToDelete);
                }
                catch (UnauthorizedAccessException ex)
                {
                    EditorObjects.IoC.Container.Get <IGlueCommands>().DialogCommands.ShowMessageBox("Success - Glue must be restarted to finish removing the plugin.");

                    using (StreamWriter w = File.AppendText(UninstallPluginFile))
                    {
                        w.WriteLine(directoryToDelete);
                    }
                }
            }
        }
示例#22
0
        public static bool RenameProject(string oldProjectName, string newProjectName)
        {
            bool           projectRenamed = false;
            ProjectManager pm             = Instance;
            TestProgramSet ts             = pm.CurrentTestProgramSet;

            if (ts != null)
            {
                string oldPath = Path.Combine(ATMLContext.TESTSET_PATH, oldProjectName);
                string newPath = Path.Combine(ATMLContext.TESTSET_PATH, newProjectName);

                try
                {
                    if (Directory.Exists(newPath))
                    {
                        LogManager.Warn("Project {0} already exists.", newProjectName);
                    }
                    else
                    {
                        CloseProject();
                        FileManager.CopyFolder(oldPath, newPath, true);
                        OpenProject(newProjectName);
                        FileManager.DeleteDirectory(oldPath, true);
                        ProjectInfo pi = ProjectInfo;
                        pi.ProjectName = newProjectName;
                        SaveProjectInfo(pi, Instance.CurrentTestProgramSet);
                        LogManager.Trace("Project {0} renamed to {1}.", oldProjectName, newProjectName);
                        //Loop through file looking for old project name - rename with new file names
                        FileManager.RenameProjectFiles(newPath, oldProjectName, newProjectName);
                        projectRenamed = true;
                    }
                }
                catch (Exception e)
                {
                    LogManager.Error(e, "Failed to rename folder {0}\n{1}", newProjectName, e.Message);
                }
            }
            return(projectRenamed);
        }
示例#23
0
        public static void UnzipScreenOrEntityImport(string fileName, out string unpackDirectory, out List <string> filesToAddToContent, out List <string> codeFiles)
        {
            codeFiles       = new List <string>();
            unpackDirectory = FileManager.UserApplicationDataForThisApplication + "Unzip\\";
            if (System.IO.Directory.Exists(unpackDirectory))
            {
                FileManager.DeleteDirectory(unpackDirectory);
            }
            System.IO.Directory.CreateDirectory(unpackDirectory);

            filesToAddToContent = new List <string>();
            string csFile      = null;
            string elementFile = null;

            using (ZipFile zip1 = ZipFile.Read(fileName))
            {
                foreach (ZipEntry zipEntry in zip1)
                {
                    string extension = FileManager.GetExtension(zipEntry.FileName);

                    if (extension == "cs")
                    {
                        codeFiles.Add(zipEntry.FileName);
                    }
                    else if (extension == "entx" || extension == "scrx")
                    {
                        elementFile = zipEntry.FileName;
                    }
                    else
                    {
                        filesToAddToContent.Add(zipEntry.FileName);
                    }

                    zipEntry.Extract(unpackDirectory, true);
                }
            }
        }
示例#24
0
        public static bool InstallPlugin(InstallationType installationType, string localPlugFile)
        {
            bool succeeded = true;


            string installPath = null;

            //Validate install path
            switch (installationType)
            {
            case InstallationType.ForUser:
                // We're now going to install to a temporary location and copy those files
                // to their final location on a restart.

                //installPath = FileManager.UserApplicationData + @"\FRBDK\Plugins\";
                installPath = FileManager.UserApplicationDataForThisApplication + "InstalledPlugins\\";

                break;

            case InstallationType.ForCurrentProject:
                if (ProjectManager.GlueProjectFileName == null)
                {
                    MessageBox.Show(@"Can not select For Current Project because no project is currently open.");
                    succeeded = false;
                }

                if (succeeded)
                {
                    Directory.CreateDirectory(FileManager.GetDirectory(ProjectManager.GlueProjectFileName) + "Plugins");

                    installPath = FileManager.GetDirectory(ProjectManager.GlueProjectFileName) + "Plugins";
                }
                break;

            default:
                MessageBox.Show(@"Unknown install type.  Please select a valid install type.");
                succeeded = false;
                break;
            }

            if (succeeded)
            {
                //Validate plugin file
                if (!File.Exists(localPlugFile))
                {
                    MessageBox.Show(@"Please select a valid *.plug file to install.");
                    succeeded = false;
                }
            }

            if (succeeded)
            {
                //Do install
                using (var zip = new ZipFile(localPlugFile))
                {
                    var rootDirectory = GetRootDirectory(zip.EntryFileNames);

                    //Only allow one folder in zip
                    if (String.IsNullOrEmpty(rootDirectory))
                    {
                        MessageBox.Show(@"Unexpected *.plug format (No root directory found in plugin archive)");
                        succeeded = false;
                    }

                    if (succeeded)
                    {
                        //Delete existing folder
                        if (Directory.Exists(installPath + @"\" + rootDirectory))
                        {
                            Plugins.PluginManager.ReceiveOutput("Plugin file already exists: " + installPath + @"\" + rootDirectory);
                            DialogResult result = MessageBox.Show(@"Existing plugin already exists!  Do you want to replace it?", @"Confirm delete", MessageBoxButtons.YesNo);

                            if (result == DialogResult.Yes)
                            {
                                try
                                {
                                    FileManager.DeleteDirectory(installPath + rootDirectory);
                                }
                                catch (Exception exc)
                                {
                                    MessageBox.Show("Error trying to delete " + installPath + @"\" + rootDirectory + "\n\n" + exc.ToString());
                                    succeeded = false;
                                }
                            }
                            else
                            {
                                succeeded = false;
                            }
                        }

                        if (succeeded)
                        {
                            //Extract into install path
                            zip.ExtractAll(installPath);

                            Plugins.PluginManager.ReceiveOutput("Installed to " + installPath);

                            MessageBox.Show(@"Successfully installed.  Restart Glue to use the new plugin.");
                        }
                        else
                        {
                            MessageBox.Show("Failed to install plugin.");
                        }
                    }
                }
            }

            return(succeeded);
        }
示例#25
0
        public static void ExportGroup(IEnumerable <IElement> elementGroup)
        {
            string directoryToExportTo = FileManager.UserApplicationDataForThisApplication + "ExportTemp\\";
            bool   succeeded           = true;

            if (Directory.Exists(directoryToExportTo))
            {
                try
                {
                    FileManager.DeleteDirectory(directoryToExportTo);
                }
                catch (Exception e)
                {
                    GlueGui.ShowMessageBox("Failed to delete the target export directory: \n" + e.ToString());
                    succeeded = false;
                }
            }

            Directory.CreateDirectory(directoryToExportTo);

            // If a single Entity is exported it must be self-contained
            // to be exported (it can't reference files outside of its relative
            // directory.  If a group of Entities are exported they may share files.
            // Therefore, we will populate the filesReferencedByElements List to suppress
            // warnings about files not referenced when they are part of the group.
            List <string> filesReferencedByElements = new List <string>();

            foreach (IElement element in elementGroup)
            {
                // We don't want to do this recursively - only the elements that
                // have been selected for export.
                foreach (ReferencedFileSave rfs in element.ReferencedFiles)
                {
                    string absoluteFile = ProjectManager.MakeAbsolute(rfs.Name, true);

                    absoluteFile = FileManager.Standardize(absoluteFile, null, false).ToLower();

                    filesReferencedByElements.Add(absoluteFile);
                }
            }

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

            foreach (IElement element in elementGroup)
            {
                if (!succeeded)
                {
                    break;
                }
                const bool openDirectory = false;

                string directoryForElement = directoryToExportTo + FileManager.GetDirectory(element.Name, RelativeType.Relative);
                Directory.CreateDirectory(directoryForElement);
                string outputFile = ExportElementToDirectory(element, directoryForElement, openDirectory, filesReferencedByElements, true);
                succeeded = !string.IsNullOrEmpty(outputFile);
                if (succeeded)
                {
                    filesToEmbed.Add(outputFile);
                }
            }

            if (succeeded)
            {
                // Create a zip that contains all the .entz and .scrz files
                SaveFileDialog fileDialog = new SaveFileDialog();
                fileDialog.Filter = "Glue Group (*.ggpz)|*.ggpz";
                DialogResult result = fileDialog.ShowDialog();

                if (result != DialogResult.Cancel)
                {
                    string whereToSaveFile = null;

                    whereToSaveFile = fileDialog.FileName;
                    using (ZipFile zip = new ZipFile())
                    {
                        foreach (string file in filesToEmbed)
                        {
                            string directoryInZip = FileManager.GetDirectory(FileManager.MakeRelative(file, directoryToExportTo), RelativeType.Relative);
                            zip.AddFile(file, directoryInZip);
                        }

                        zip.Save(whereToSaveFile);
                    }


                    string locationToShow = "\"" + whereToSaveFile + "\"";
                    locationToShow = locationToShow.Replace("/", "\\");
                    Process.Start("explorer.exe", "/select," + locationToShow);
                }
            }
        }
示例#26
0
        /// <summary>
        /// Invoke the method specified by the
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </summary>
        /// <param name="message">
        /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object
        /// </param>
        internal async override void InvokeAsync(JSMessage message)
        {
            string callbackId = message.CallbackId;

            FilePath options =
                JsonConvert.DeserializeObject <FilePath>(message.Args[message.Args.Length - 1].ToString());

            // Set the file path in FilePath options
            // Normal file operations get path as first parameter and options as second
            // Unzip method receives a file object with path in it already.
            if (!message.Method.Equals("unzip"))
            {
                options.Path = message.Args[0] as string;
            }


            string path;

            try
            {
                switch (message.Method)
                {
                case "deleteDirectory":
                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Delete directory
                    try
                    {
                        FileManager.DeleteDirectory(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "deleteFile":

                    // Get the absolute path
                    //Open : Ask
                    path = FileManager.GetAbsolutePath(options, false);

                    // Delete file
                    try
                    {
                        FileManager.DeleteFile(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getDirectory":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Create directory
                    try
                    {
                        FileManager.CreateDirectory(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getFile":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Create file
                    try
                    {
                        FileManager.CreateFile(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "getFilesJSONString":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Get files list
                    Tuple <bool, List <Dictionary <string, object> >, string> getFilesResult =
                        await FileManager.GetFoldersAndFilesAsync(path, options.StorageType);

                    if (getFilesResult.Item1)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Result = getFilesResult.Item2
                        });
                    }
                    else
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = getFilesResult.Item3
                            }
                        });
                    }
                    break;

                case "getRootDirectory":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Return root directory
                    InvokeCallbackJavascript(callbackId, new MethodResult {
                        Result = path
                    });
                    break;

                case "read":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Read file
                    try
                    {
                        string fileContentStr = FileManager.ReadAsString(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = fileContentStr
                        });
                    }
                    catch (Exception e)
                    {
                        Logger.Error("File not found" + e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND)
                            }
                        });
                    }
                    break;

                case "readData":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Read file
                    try
                    {
                        string fileContentData = Convert.ToBase64String(FileManager.ReadAsBytes(path));
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = fileContentData
                        });
                    }
                    catch (Exception e)
                    {
                        Logger.Error("File not found" + e.Message);
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND)
                            }
                        });
                    }
                    break;

                case "testDirExists":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Test dir exists
                    try
                    {
                        bool isDirExists = FileManager.DirectoryExists(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = isDirExists
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "testFileExists":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Test file exists
                    try
                    {
                        bool isFileExists = FileManager.FileExists(path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = isFileExists
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "unzip":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options, false);

                    // Source file
                    FilePath srcFileOptions = JsonConvert.DeserializeObject <FilePath>(message.Args[0].ToString());
                    string   srcFilePath    = FileManager.GetAbsolutePath(srcFileOptions, false);

                    if (!FileManager.FileExists(srcFilePath))
                    {
                        throw new Exception(Mowbly.GetString(Constants.STRING_FILE_NOT_FOUND));
                    }

                    // Unzip
                    try
                    {
                        FileManager.unzip(srcFilePath, path);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "write":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Write content to file
                    try
                    {
                        string fileContentStr      = message.Args[1] as string;
                        bool   shouldAppendContent = (bool)message.Args[2];
                        FileManager.WriteStringToFile(path, fileContentStr, shouldAppendContent);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                case "writeData":

                    // Get the absolute path
                    path = FileManager.GetAbsolutePath(options);

                    // Write content to file
                    try
                    {
                        byte[] fileContentBytes    = Convert.FromBase64String(message.Args[0] as string);
                        bool   shouldAppendContent = (bool)message.Args[1];
                        FileManager.WriteDataToFile(path, fileContentBytes, shouldAppendContent);
                        InvokeCallbackJavascript(callbackId, new MethodResult {
                            Result = true
                        });
                    }
                    catch (Exception e)
                    {
                        InvokeCallbackJavascript(callbackId, new MethodResult
                        {
                            Code   = MethodResult.FAILURE_CODE,
                            Result = false,
                            Error  = new MethodError
                            {
                                Message = e.Message
                            }
                        });
                    }
                    break;

                default:
                    Logger.Error("Feature " + Name + " does not support method " + message.Method);
                    break;
                }
            }
            catch (Exception ce)
            {
                Logger.Error("Exception occured. Reason - " + ce.Message);
            }
        }
示例#27
0
 /// <summary>Cleanup temporary files.</summary>
 public void Cleanup()
 {
     FileManager.DeleteDirectory(_downloadPath);
 }
示例#28
0
    private void Deploy()
    {
        try
        { Debug.Log(SettingsManager.DEPLOY_PATH); Debug.Log(SettingsManager.BUILDS_PATH); Debug.Log(SettingsManager.APP_PATH);
          // Cache current build target
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Caching current build target...", 0);
          BuildTarget      cachedTarget      = EditorUserBuildSettings.activeBuildTarget;
          BuildTargetGroup cachedTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;

          // Copy selected build in deploy environment
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Checking deploy directory...", 0.1f);
          if (FileManager.DirectoryExists(SettingsManager.DEPLOY_PATH + _currentVersions[_versionToDeployDropdownIndex]))
          {
              FileManager.DeleteDirectory(SettingsManager.DEPLOY_PATH + _currentVersions[_versionToDeployDropdownIndex]);
          }
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Copying selected build...", 0.2f);
          FileManager.CopyDirectory(SettingsManager.BUILDS_PATH + Path.DirectorySeparatorChar + _currentVersions[_versionToDeployDropdownIndex], SettingsManager.DEPLOY_PATH + _currentVersions[_versionToDeployDropdownIndex]);

          // Build selected Launcher scene
          BuildTarget      target      = (BuildTarget)Enum.Parse(typeof(BuildTarget), _platformsAvailable[_platformToDeployDropdownIndex]);
          BuildTargetGroup targetGroup = BuildTargetGroup.Standalone;
          EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, target);
          BuildPipeline.BuildPlayer(new string[] { _scenesInBuildSettings[_launcherSceneToDeployDropdownIndex] },
                                    Path.Combine(SettingsManager.DEPLOY_PATH, _currentVersions[_versionToDeployDropdownIndex] + Path.DirectorySeparatorChar + _launcherCustomName + GetAppExtension(target)),
                                    target, BuildOptions.None);

          FileManager.DeleteFiles(Path.Combine(SettingsManager.DEPLOY_PATH, _currentVersions[_versionToDeployDropdownIndex]), "*.pdb");

          // ZIP generated application
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Compressing deployed build...", 0.5f);
          MHLab.PATCH.Compression.CompressionType ctype;
          string sCType = _compressionTypes[_deployCompressionTypeDropdownIndex];
          switch (sCType)
          {
          case "ZIP": ctype = MHLab.PATCH.Compression.CompressionType.ZIP; break;

          case "TAR": ctype = MHLab.PATCH.Compression.CompressionType.TAR; break;

          case "TARGZ": ctype = MHLab.PATCH.Compression.CompressionType.TARGZ; break;

          default: ctype = MHLab.PATCH.Compression.CompressionType.TAR; break;
          }
          m_patchManager.DeployCompress(
              Path.Combine(SettingsManager.DEPLOY_PATH, _currentVersions[_versionToDeployDropdownIndex]),
              Path.Combine(SettingsManager.DEPLOY_PATH, _launcherCustomName + "_" + _currentVersions[_versionToDeployDropdownIndex] + "_" + _platformsAvailable[_platformToDeployDropdownIndex] + ".zip"),
              ctype
              );

          // Clean up useless files
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Cleaning up...", 0.9f);
          FileManager.DeleteDirectory(Path.Combine(SettingsManager.DEPLOY_PATH, _currentVersions[_versionToDeployDropdownIndex]));

          // Restore original build target
          EditorUtility.DisplayProgressBar("P.A.T.C.H.", "Finalization...", 1f);
          EditorUserBuildSettings.SwitchActiveBuildTarget(cachedTargetGroup, cachedTarget);
          EditorUtility.ClearProgressBar(); }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }