private static IEnumerable <Process> GetInstances() { if (Attributes.AppWaitFull < 0) { return(ProcessEx.GetInstances(Attributes.AppPath, true)); } if (_instanceDirs == default(List <string>)) { _instanceDirs = new List <string>(); switch (Attributes.AppWaitFull) { case 0: case 1: _instanceDirs.Add(Attributes.AppDir); _instanceDirs.Add(Attributes.DataDir); break; default: _instanceDirs.Add(PathEx.LocalDir); if (Attributes.DirMap?.Any() == true) { var fromKeys = Attributes.DirMap.Keys.Where(x => !x.StartsWithEx(PathEx.LocalDir)).ToArray(); if (fromKeys.Any()) { _instanceDirs.AddRange(fromKeys); } var fromValues = Attributes.DirMap.Values.Where(x => !x.StartsWithEx(PathEx.LocalDir)).ToArray(); if (fromValues.Any()) { _instanceDirs.AddRange(fromValues); } } break; } if (Attributes.AppWaitDirs?.Any() == true) { _instanceDirs.AddRange(Attributes.AppWaitDirs); } _instanceDirs = _instanceDirs.Select(PathEx.Combine).Distinct().ToList(); } var files = new List <string>(); foreach (var dir in _instanceDirs.Where(Directory.Exists)) { files.AddRange(DirectoryEx.GetFiles(dir, "*.exe", SearchOption.AllDirectories).Where(x => !x.EqualsEx(PathEx.LocalPath))); } files = (Attributes.IgnoredProcesses?.Any() == true ? files.Distinct().Where(x => !Attributes.IgnoredProcesses.ContainsEx(Path.GetFileName(x), Path.GetFileNameWithoutExtension(x))) : files.Distinct()).ToList(); return(files.SelectMany(x => ProcessEx.GetInstances(Attributes.AppWaitFull == 0 ? Path.GetFileName(x) : x, Attributes.AppWaitFull >= 2)).Distinct().Where(x => x.Handle != ProcessEx.CurrentHandle)); }
private static void CopyOldTools(string outerToolsFolderPath, ILongWaitBroker broker) { //Copy tools to a different folder then Directory.Move if successful. string tempOuterToolsFolderPath = string.Concat(outerToolsFolderPath, "_installing"); // Not L10N if (Directory.Exists(tempOuterToolsFolderPath)) { DirectoryEx.SafeDelete(tempOuterToolsFolderPath); // Not sure this is necessay, but just to be safe if (Directory.Exists(tempOuterToolsFolderPath)) { throw new Exception(Resources.Program_CopyOldTools_Error_copying_external_tools_from_previous_installation); } } // Must create the tools directory to avoid ending up here again next time Directory.CreateDirectory(tempOuterToolsFolderPath); ToolList toolList = Settings.Default.ToolList; int numTools = toolList.Count; const int endValue = 100; int progressValue = 0; int increment = (endValue - progressValue) / (numTools + 1); foreach (var tool in toolList) { string toolDirPath = tool.ToolDirPath; if (!string.IsNullOrEmpty(toolDirPath) && Directory.Exists(toolDirPath)) { string foldername = Path.GetFileName(toolDirPath); string newDir = Path.Combine(outerToolsFolderPath, foldername); string tempNewDir = Path.Combine(tempOuterToolsFolderPath, foldername); if (!Directory.Exists(tempNewDir)) { DirectoryEx.DirectoryCopy(toolDirPath, tempNewDir, true); } tool.ToolDirPath = newDir; // Update the tool to point to its new directory. tool.ArgsCollectorDllPath = tool.ArgsCollectorDllPath.Replace(toolDirPath, newDir); } if (broker.IsCanceled) { // Don't leave around a corrupted directory DirectoryEx.SafeDelete(tempOuterToolsFolderPath); return; } progressValue += increment; broker.ProgressValue = progressValue; } Directory.Move(tempOuterToolsFolderPath, outerToolsFolderPath); Settings.Default.ToolList = ToolList.CopyTools(toolList); }
public void Extract(IProgressMonitor progressMonitor) { ProgressMonitor = progressMonitor; ProgressMonitor.UpdateProgress(_progressStatus = new ProgressStatus(DefaultMessage)); var extractDir = ExtractDir(SharedPath); using (ZipFile zip = ZipFile.Read(SharedPath)) { CountEntries = zip.Entries.Count; ExpectedSize = zip.Entries.Select(entry => entry.UncompressedSize).Sum(); zip.ExtractProgress += SrmDocumentSharing_ExtractProgress; string documentName = FindSharedSkylineFile(zip); string parentDir = Path.GetDirectoryName(SharedPath); if (!string.IsNullOrEmpty(parentDir)) { extractDir = Path.Combine(parentDir, extractDir); } extractDir = GetNonExistentDir(extractDir); DocumentPath = Path.Combine(extractDir, documentName); foreach (var entry in zip.Entries) { if (ProgressMonitor.IsCanceled) { break; } try { entry.Extract(extractDir); ExtractedSize += entry.UncompressedSize; } catch (Exception) { if (!ProgressMonitor.IsCanceled) { throw; } } } } if (ProgressMonitor.IsCanceled) { DirectoryEx.SafeDelete(extractDir); } }
private IEnumerable <string> AllMatchingFilesInFolder(string path, bool skipProjectOutputFolders = true) { if (skipProjectOutputFolders && ProjectOutputFolders.Any(p => string.Equals(Path.Combine(ProjectFolder, p), path, StringComparison.CurrentCultureIgnoreCase))) { return(new string[0]); } return (DirectoryEx .GetFilesExceptOutput(path, _pattern) .Where(p => _excludedExtensions.Contains(new FileInfo(p).Extension.ToLower()) == false)); }
private static FileStream EnsurePluginConf(ISMAPlugin plugin, Type confType, FileAccess fileAccess) { string filePath = Path.Combine(SMAConst.Paths.ConfigPath, plugin.Id.ToString("D")); if (!DirectoryEx.EnsureExists(filePath)) { return(null); } filePath = Path.Combine(filePath, confType.Name); return(File.Open(filePath, fileAccess == FileAccess.Read ? FileMode.OpenOrCreate : FileMode.Create, fileAccess)); }
public bool Save() { bool IsOk = true; DirectoryEx.DeleteFolder1(Path); if (!DirectoryEx.Exist(Path)) { DirectoryEx.Create(Path); } IsOk = IsOk && XML <LightCrlParaManager> .Write(this, Path + @"\" + "LightCrlParaManager.xml"); return(IsOk); }
public bool Save() { bool IsOk = true; DirectoryEx.Delete(ParaPath); if (!DirectoryEx.Exist(ParaPath)) { DirectoryEx.Create(ParaPath); } IsOk = IsOk && XML <BindingList <CameraPara> > .Write(CameraParaList, ParaPath + @"\" + "CameraParaList.xml"); return(IsOk); }
private async Task OnSMStarted(object sender, SMProcessArgs e) { LogTo.Debug($"Initializing {GetType().Name}"); DirectoryEx.EnsureExists(SMAFileSystem.PluginPackageDir.FullPath); StartIpcServer(); //StartMonitoringPlugins(); await RefreshPlugins(); await StartPlugins(); }
public void AddToolsSolutionDirectoryToAddinSearch() { var solutionDirToolsDirectory = Path.Combine(solutionDirectory, "Tools"); if (!Directory.Exists(solutionDirToolsDirectory)) { log($" Skipped scanning '{solutionDirToolsDirectory}' since it doesn't exist."); return; } log($" Scanning SolutionDir/Tools directory convention: '{solutionDirToolsDirectory}'."); AddFiles(DirectoryEx.EnumerateFilesEndsWith(solutionDirToolsDirectory, ".Fody.dll", SearchOption.AllDirectories)); }
public void GetFile_RelativePath_Exists() { // arrange var dir = new DirectoryEx(".\\Sample"); // act var got = dir.TryGetFile("KSW Doradztwo\\.dirrc.json", out var file); // assert got.Should().BeTrue(); file.Should().NotBeNull(); file.Name.Should().Be(".dirrc.json"); }
private void CreateFile(string relativePath, Blob target) { string path = PathEx.Combine(this.rootPath, relativePath); string directory = PathEx.GetDirectoryName(path); DirectoryEx.Create(directory); using (var targetStream = target.GetContentStream()) using (var file = FileEx.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { targetStream.CopyTo(file); } }
void BackupCreate(bool manual = false) { DirectoryEx.Backup(BackupFolders()); DirectoryEx.CopyAll(ConVar.Server.rootFolder, backupFolders[0]); if (includeOxideInBackups) { DirectoryEx.CopyAll("oxide", backupFoldersOxide[0]); } if (!manual) { Puts(lang.GetMessage("backupfinish", this)); } }
public void WalkDown_RelativePath_Exists1() { // arrange var dir = new DirectoryEx(".\\Sample"); // act var results = dir.WalkDown("KSW Doradztwo\\2018").ToArray(); // assert results.Should().HaveCount(2); results[0].Name.Should().Be("KSW Doradztwo"); results[1].Name.Should().Be("2018"); }
public void Run() { try { DirectoryEx.EnsureExists(this.PackagesBackupPath); IList <PackageEdit> edits; using (var connection = this.PackageDatabase.ConnectTo()) { edits = connection.Query <PackageEdit>(GetEditsBaseSql).ToList(); } Log.Info("Fetched {2} queued edits from {0}/{1}", PackageDatabase.DataSource, PackageDatabase.InitialCatalog, edits.Count); // Group by package and take just the most recent edit for each package edits = edits.GroupBy(e => e.PackageKey) .Select(g => g.OrderByDescending(e => e.Timestamp).FirstOrDefault()) .Where(e => e != null) .ToList(); foreach (var edit in edits) { Exception thrown = null; try { this.ApplyEdit(edit); } catch (Exception ex) { thrown = ex; } if (thrown != null) { using (var connection = this.PackageDatabase.ConnectTo()) { connection.Query <int>(@" UPDATE PackageEdits SET TriedCount = TriedCount + 1, LastError = @error WHERE [Key] = @key", new { error = thrown.ToString(), key = edit.Key }); } } } } finally { DirectoryEx.TryDelete(this.PackagesTempPath); } }
/// <inheritdoc /> public void LaunchUpdater(Version version, bool restart, string restartArguments) { // Ensure that the current state is valid for this operation EnsureNotDisposed(); EnsureLockFileAcquired(); EnsureUpdaterNotLaunched(); EnsureUpdatePrepared(version); // Get package content directory path var packageContentDirPath = GetPackageContentDirPath(version); // Get original command line arguments and encode them to avoid issues with quotes var routedArgs = restartArguments.GetBytes().ToBase64(); // Prepare arguments var updaterArgs = $"\"{Updatee.FilePath}\" \"{packageContentDirPath}\" \"{restart}\" \"{routedArgs}\""; // Decide if updater needs to be elevated var updateeDirPath = Path.GetDirectoryName(Updatee.FilePath); var isUpdaterElevated = !string.IsNullOrWhiteSpace(updateeDirPath) && !DirectoryEx.CheckWriteAccess(updateeDirPath); // Create updater process start info var updaterStartInfo = new ProcessStartInfo(); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { updaterStartInfo.FileName = _updaterFilePath; updaterStartInfo.Arguments = updaterArgs; updaterStartInfo.CreateNoWindow = true; updaterStartInfo.UseShellExecute = false; } else { updaterStartInfo.FileName = "dotnet"; updaterStartInfo.Arguments = $"{_updaterFilePath} {updaterArgs}"; } // If updater needs to be elevated - use shell execute with "runas" if (isUpdaterElevated) { updaterStartInfo.Verb = "runas"; updaterStartInfo.UseShellExecute = true; } // Create and start updater process var updaterProcess = new Process { StartInfo = updaterStartInfo }; using (updaterProcess) updaterProcess.Start(); }
public void WalkDown_RelativePath_Exists4() { // arrange var dir = new DirectoryEx(".\\Sample"); // act var results = dir.WalkDown("\\PZ Solutions\\2018").ToArray(); // assert results.Should().HaveCount(3); results[0].Name.Should().Be($"{Path.DirectorySeparatorChar}"); results[1].Name.Should().Be("PZ Solutions"); results[2].Name.Should().Be("2018"); }
void OnPluginUnloaded(Plugin name) { if (Interface.Oxide.IsShuttingDown && !wasShutDown) { wasShutDown = true; try { DirectoryEx.Backup(BackupFoldersShutdown()); if (includeOxideInBackups) { DirectoryEx.Backup(BackupFoldersShutdownOxide()); } } catch {} } }
static IEnumerable <AssemblyAndVersion> EnumerateOldStyleDirectories(string directory) { foreach (var versionDirectory in DirectoryEx.EnumerateDirectoriesContains(directory, ".fody.")) { var fileName = Path.GetFileName(versionDirectory); var index = fileName.IndexOf(".fody.", StringComparison.OrdinalIgnoreCase); var packageName = fileName.Substring(0, index + 5); var version = Version.Parse(fileName.Substring(index + 6).Split('-')[0]); yield return(new AssemblyAndVersion { Version = version, Assembly = GetAssemblyFromNugetDir(versionDirectory, packageName) }); } }
public static void UnblockLogs() { foreach (string str in Paths.Elsword.LogFiles.Where <string>((string logFile) => { if (!PathEx.Exists(logFile)) { return(true); } return(!PathEx.IsFile(logFile)); })) { PathEx.RemoveAttributes(str); DirectoryEx.Delete(str); } }
IEnumerable <string> EnumerateToolsSolutionDirectoryWeavers() { var solutionDirToolsDirectory = Path.Combine(solutionDirectory, "Tools"); if (!Directory.Exists(solutionDirToolsDirectory)) { log($" Skipped scanning '{solutionDirToolsDirectory}' since it doesn't exist."); return(Enumerable.Empty <string>()); } log($" Scanning SolutionDir/Tools directory convention: '{solutionDirToolsDirectory}'."); return(DirectoryEx.EnumerateFilesEndsWith(solutionDirToolsDirectory, WeaverDllSuffix, SearchOption.AllDirectories)); }
/// <summary>获取所有缓存文件的大小,单位字节</summary> public long Length() { long capacity = 0; FileInfo[] filesArr = DirectoryEx.GetFiles(CacheDefine.CachePath); for (int i = 0; i < filesArr.Length; i++) { FileInfo fileInfo = filesArr[i]; capacity += fileInfo.Length; } return(capacity); }
public void WalkUp_RelativePath_Exists1() { // arrange var dir = new DirectoryEx(".\\Sample") .GetNestedDirectory("KSW Doradztwo\\2018\\\\PZ Solutions\\2018"); // act var results = dir.WalkUp().ToArray(); // assert results.Should().HaveCount(3); results[0].Name.Should().Be("2018"); results[1].Name.Should().Be("PZ Solutions"); results[2].Name.Should().Be($"{Path.DirectorySeparatorChar}"); }
private void CreateAndConfigureProgramDataDirectories() { string serviceDataRootPath = ScalarPlatform.Instance.GetSecureDataRootForScalar(); // Create Scalar.Service and Scalar.Upgrade related directories (if they don't already exist) // TODO #136: Determine if we still should be creating Scalar.Service here DirectoryEx.CreateDirectory(serviceDataRootPath); DirectoryEx.CreateDirectory(this.serviceDataLocation); DirectoryEx.CreateDirectory(ProductUpgraderInfo.GetUpgradeProtectedDataDirectory()); // Special rules for the upgrader logs and registry, as non-elevated users need to be be able to write this.CreateAndConfigureUserWriteableDirectory(this.repoRegistryLocation); this.CreateAndConfigureUserWriteableDirectory(ProductUpgraderInfo.GetLogDirectoryPath()); this.CreateAndConfigureUserWriteableDirectory(ScalarPlatform.Instance.GetLogsDirectoryForGVFSComponent(ScalarConstants.Service.UIName)); }
private static void ClearTmpPathFiles() { try { if (Directory.GetFiles(PathEx.TmpPath).Length > 0) { DirectoryEx.DeleteC(PathEx.TmpPath, true); Directory.CreateDirectory(PathEx.TmpPath); } } catch (Exception e) { Log.Exception(e); } }
protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context) { var projectFullPath = context.ResolvePath(this.ProjectPath); this.LogInformation($"Building {projectFullPath}..."); var buildProperties = string.Join(";", this.MSBuildProperties ?? Enumerable.Empty <string>()); var config = "Configuration=" + this.BuildConfiguration; if (!string.IsNullOrEmpty(this.TargetPlatform)) { config += ";Platform=" + this.TargetPlatform; } if (!string.IsNullOrEmpty(buildProperties)) { config += ";" + buildProperties; } var args = $"\"{projectFullPath}\" \"/p:{config}\""; if (!string.IsNullOrWhiteSpace(this.TargetDirectory)) { args += $" \"/p:OutDir={context.ResolvePath(this.TargetDirectory).TrimEnd('\\')}\\\\\""; } if (!string.IsNullOrWhiteSpace(this.AdditionalArguments)) { args += " " + this.AdditionalArguments; } var workingDir = PathEx.GetDirectoryName(projectFullPath); if (!DirectoryEx.Exists(workingDir)) { throw new DirectoryNotFoundException($"Directory {workingDir} does not exist."); } int result = await this.InvokeMSBuildAsync(context, args, workingDir).ConfigureAwait(false); if (result != 0) { this.LogError($"Build failed (msbuild returned {result})."); } return(null); }
/// <summary> /// Creates a directory to the path specified if it's found to be nonexistent. /// Returns a <see cref="DirectoryInfo"/> object for the directory created. /// </summary> /// <param name="path">The path of the directory.</param> /// <param name="directoryName"> /// Name of the directory. This will placed in the <see cref="IErrorDialogService"/> message showing /// the user which directory couldn't be created should an <see cref="Exception"/> be thrown. /// </param> private DirectoryInfo CreateDirectoryIfNonexistent(string path, string directoryName) { var message = String.Empty; DirectoryInfo directoryInfo = null; try { directoryInfo = DirectoryEx.CreateDirectoryIfNonexistent(path); } catch (PathTooLongException) { message = $"The \"{directoryName}\" directory couldn't be created because the resulting path would be too long."; ErrorDialogService.Show(message); } catch (UnauthorizedAccessException) { message = $"The \"{directoryName}\" directory couldn't be created because this application doesn't have access to the destination."; ErrorDialogService.Show(message); } catch (ArgumentException) { message = $"The \"{directoryName}\" directory couldn't be created because the path is prefixed with, or contains, only a colon character (:)."; ErrorDialogService.Show(message); } catch (DirectoryNotFoundException) { message = $"The \"{directoryName}\" directory couldn't be created because the path was invalid (for example, it's on an unmapped drive)."; ErrorDialogService.Show(message); } catch (IOException) { message = $"The \"{directoryName}\" directory couldn't be created because the specified path is a file, or the network name isn't known."; ErrorDialogService.Show(message); } catch (NotSupportedException) { message = $"The \"{directoryName}\" directory couldn't be created because the path contains a colon character (:) that is not part of a drive label."; ErrorDialogService.Show(message); } catch (Exception e) { Console.WriteLine(e.Message); ErrorDialogService.Show(e.Message); throw; } return(directoryInfo); }
private static void CopyBaseFile(string destDir) { var maxVerPath = GetMaxVersionPath(); if (string.IsNullOrEmpty(maxVerPath)) { //NetUtil.DownFile(baseDownloadUrl, _baseFn, baseLength); //Zip.UnZipFile(_baseFn, destDir, null); Log.Info("缺少基础版本.....无法升级到最新版"); //MsgBox.ShowErrTip("无法升级到最新版....请手动安装!!"); } else { DirectoryEx.Copy(maxVerPath, destDir); } }
public override object ProvideValue(IServiceProvider serviceProvider) { if (!String.IsNullOrEmpty(FullPath)) { if (DirectoryEx.Exists(FullPath)) { return(new DirectoryInfoEx(FullPath)); } else { return(new FileInfoEx(FullPath)); } } return(DirectoryInfoEx.DesktopDirectory); }
private void CancelBtn_Click(object sender, EventArgs e) { try { if (Transferor.IsBusy) { Transferor.CancelAsync(); } DirectoryEx.Delete(CachePaths.UpdateDir); } catch (Exception ex) when(ex.IsCaught()) { Log.Write(ex); } Application.Exit(); }
public void TestDeleteContents() { using (var dir = new TemporaryDirectory()) { var subDirPath = Path.Combine(dir.Path, "subDir"); var subDirFilePath = Path.Combine(subDirPath, "file"); var filePath = Path.Combine(dir.Path, "file"); Directory.CreateDirectory(subDirPath); File.WriteAllText(subDirFilePath, ""); File.WriteAllText(filePath, ""); DirectoryEx.DeleteContents(dir.Path); Assert.IsFalse(File.Exists(filePath)); Assert.IsFalse(Directory.Exists(subDirPath)); Assert.IsTrue(Directory.Exists(dir.Path)); } }