async Task<bool> TryCheckUac(IAbsoluteDirectoryPath mp, IAbsoluteFilePath path) { Exception ex; try { mp.MakeSurePathExists(); if (path.Exists) File.Delete(path.ToString()); using (File.CreateText(path.ToString())) {} File.Delete(path.ToString()); return false; } catch (UnauthorizedAccessException e) { ex = e; } catch (Exception e) { this.Logger().FormattedWarnException(e); return false; } var report = await UserErrorHandler.HandleUserError(new UserErrorModel("Restart the application elevated?", $"The application failed to write to the path, probably indicating permission issues\nWould you like to restart the application Elevated?\n\n {mp}", RecoveryCommands.YesNoCommands, null, ex)) == RecoveryOptionResultModel.RetryOperation; if (!report) return false; RestartWithUacInclEnvironmentCommandLine(); return true; }
static void DeleteDestinationIfDirectory(IAbsoluteFilePath backupDestination) { if (Directory.Exists(backupDestination.ToString())) { backupDestination.ToString().ToAbsoluteDirectoryPath().Delete(true); } }
void CleanupInfo() { if (_versionInfoFile.Exists) { Tools.FileUtil.Ops.DeleteWithRetry(_versionInfoFile.ToString()); } }
async Task TryDownloadAsync(TransferSpec spec, IWebClient webClient, IAbsoluteFilePath tmpFile) { try { tmpFile.RemoveReadonlyWhenExists(); if (!string.IsNullOrWhiteSpace(spec.Uri.UserInfo)) webClient.SetAuthInfo(spec.Uri); using (webClient.HandleCancellationToken(spec)) await webClient.DownloadFileTaskAsync(spec.Uri, tmpFile.ToString()).ConfigureAwait(false); VerifyIfNeeded(spec, tmpFile); _fileOps.Move(tmpFile, spec.LocalFile); } catch (OperationCanceledException e) { _fileOps.DeleteIfExists(tmpFile.ToString()); throw CreateTimeoutException(spec, e); } catch (WebException ex) { _fileOps.DeleteIfExists(tmpFile.ToString()); var cancelledEx = ex.InnerException as OperationCanceledException; if (cancelledEx != null) throw CreateTimeoutException(spec, cancelledEx); if (ex.Status == WebExceptionStatus.RequestCanceled) throw CreateTimeoutException(spec, ex); var response = ex.Response as HttpWebResponse; if (response == null) throw GenerateDownloadException(spec, ex); switch (response.StatusCode) { case HttpStatusCode.NotFound: throw new RequestFailedException("Received a 404: NotFound response", ex); case HttpStatusCode.Forbidden: throw new RequestFailedException("Received a 403: Forbidden response", ex); case HttpStatusCode.Unauthorized: throw new RequestFailedException("Received a 401: Unauthorized response", ex); } throw GenerateDownloadException(spec, ex); } }
public void Move(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite = true, bool checkMd5 = false) { if (FileUtil.ComparePathsEqualCase(source.ToString(), destination.ToString())) { throw new ArgumentException("Source and destination paths cannot be equal"); } if (!source.Exists) { throw new FileNotFoundException("File doesnt exist: " + source); } if (checkMd5 && SumsAreEqual(source, destination)) { this.Logger() .Info("Source and destination files equal. Source: {0}, Destination: {1}", source, destination); if (!FileUtil.ComparePathsOsCaseSensitive(source, destination)) { DeleteIfExists(source.ToString()); } return; } source.RemoveReadonlyWhenExists(); if (FileUtil.ComparePathsOsCaseSensitive(source, destination)) { CaseChangeMove(source, destination); } else { RealMove(source, destination, overwrite); } }
async Task <bool> TryCheckUac(IAbsoluteDirectoryPath mp, IAbsoluteFilePath path) { Exception ex; try { mp.MakeSurePathExists(); if (path.Exists) { File.Delete(path.ToString()); } using (File.CreateText(path.ToString())) {} File.Delete(path.ToString()); return(false); } catch (UnauthorizedAccessException e) { ex = e; } catch (Exception e) { this.Logger().FormattedWarnException(e); return(false); } var report = await UserErrorHandler.HandleUserError(new UserErrorModel("Restart the application elevated?", $"The application failed to write to the path, probably indicating permission issues\nWould you like to restart the application Elevated?\n\n {mp}", RecoveryCommands.YesNoCommands, null, ex)) == RecoveryOptionResultModel.RetryOperation; if (!report) { return(false); } RestartWithUacInclEnvironmentCommandLine(); return(true); }
public static void ConvertLegacy2(IAbsoluteFilePath settingsFile) { var data = File.ReadAllText(settingsFile.ToString()); var newData = ProcessNamespaces2(data); File.WriteAllText(settingsFile.ToString(), newData); }
void RealMove(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite) { if (overwrite && destination.Exists && !FileUtil.ComparePathsOsCaseSensitive(source, destination)) { DeleteIfExists(destination.ToString()); } File.Move(source.ToString(), destination.ToString()); }
public Task CreateTextAsync(IAbsoluteFilePath filePath, params string[] text) => AddIORetryDialog(async() => { using (var fs = File.CreateText(filePath.ToString())) { foreach (var t in text) { await fs.WriteAsync(t).ConfigureAwait(false); } } }, filePath.ToString());
public string SHA1FileHash(IAbsoluteFilePath fileName) { Contract.Requires<ArgumentNullException>(fileName != null); return FileUtil.Ops.AddIORetryDialog(() => { using (var fs = new FileStream(fileName.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read)) using (var stream = new BufferedStream(fs, GetBufferSize(fs))) using (var md5 = new SHA1CryptoServiceProvider()) return GetHash(md5.ComputeHash(stream)); }, fileName.ToString()); }
public static void ConvertLegacy(IAbsoluteFilePath settingsFile) { var data = File.ReadAllText(settingsFile.ToString()); var newData = ProcessLocalModFolders(data); newData = ProcessLocalMissionFolders(newData); newData = ProcessModSets(newData); File.WriteAllText(settingsFile.ToString(), newData); }
public void CreateText(IAbsoluteFilePath filePath, params string[] text) { AddIORetryDialog(() => { using (var fs = File.CreateText(filePath.ToString())) { foreach (var t in text) { fs.Write(t); } } }, filePath.ToString()); }
public string SHA1FileHash(IAbsoluteFilePath fileName) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } return(FileUtil.Ops.AddIORetryDialog(() => { using (var fs = new FileStream(fileName.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read)) //using (var stream = new BufferedStream(fs, GetBufferSize(fs))) using (var md5 = SHA1.Create()) return GetHash(md5.ComputeHash(fs)); }, fileName.ToString())); }
static bool InstallDll(IAbsoluteFilePath pluginPath, IAbsoluteDirectoryPath gamePluginFolder, bool force = true) { if (gamePluginFolder == null) { throw new ArgumentNullException(nameof(gamePluginFolder)); } if (pluginPath == null) { throw new ArgumentNullException(nameof(pluginPath)); } if (!pluginPath.IsNotNullAndExists()) { throw new PathDoesntExistException(pluginPath.ToString()); } if (!gamePluginFolder.IsNotNullAndExists()) { throw new PathDoesntExistException(gamePluginFolder.ToString()); } var fullPath = gamePluginFolder.GetChildFileWithName(pluginPath.FileName); if (!force && fullPath.Exists) { return(false); } return(TryCopyDll(pluginPath, fullPath)); }
public static IEnumerable<string> GenerateCommandLineExecution(IAbsoluteFilePath location, string executable, params string[] desiredParams) { var updateExe = GetUpdateExe(location); return (updateExe != null) && updateExe.Exists ? new[] {updateExe.ToString()}.Concat(Restarter.BuildUpdateExeArguments(executable, desiredParams)) : new[] {location.ToString()}.Concat(desiredParams); }
void DeleteSourceFileIfExists() { if (_sourceFile.Exists) { Tools.FileUtil.Ops.DeleteWithRetry(_sourceFile.ToString()); } }
public virtual string Gzip(IAbsoluteFilePath file, IAbsoluteFilePath dest = null, bool preserveFileNameAndModificationTime = false) { Contract.Requires<ArgumentNullException>(file != null); Contract.Requires<ArgumentException>(file.Exists); var defDest = (file + ".gz").ToAbsoluteFilePath(); if (dest == null) dest = defDest; var cmd = String.Format("-f --best --rsyncable --keep \"{0}\"", file); if (!preserveFileNameAndModificationTime) cmd = "-n " + cmd; dest.RemoveReadonlyWhenExists(); var startInfo = new ProcessStartInfoBuilder(Common.Paths.ToolPath.GetChildFileWithName("gzip.exe"), cmd) { WorkingDirectory = file.ParentDirectoryPath.ToString() }.Build(); var ret = ProcessManager.LaunchAndGrabTool(startInfo, "Gzip pack"); if (Path.GetFullPath(dest.ToString()) != Path.GetFullPath(defDest.ToString())) FileUtil.Ops.MoveWithRetry(defDest, dest); return ret.StandardOutput + ret.StandardError; }
public virtual string Gzip(IAbsoluteFilePath file, IAbsoluteFilePath dest = null, bool preserveFileNameAndModificationTime = true, ITProgress status = null) { Contract.Requires<ArgumentNullException>(file != null); Contract.Requires<ArgumentException>(file.Exists); var defDest = (file + ".gz").ToAbsoluteFilePath(); if (dest == null) dest = defDest; var cmd = $"-f --best --rsyncable --keep \"{file}\""; if (!preserveFileNameAndModificationTime) cmd = "-n " + cmd; dest.RemoveReadonlyWhenExists(); var startInfo = new ProcessStartInfoBuilder(Common.Paths.ToolPath.GetChildFileWithName("gzip.exe"), cmd) { WorkingDirectory = file.ParentDirectoryPath }.Build(); var srcSize = file.FileInfo.Length; ProcessExitResultWithOutput ret; var predictedSize = srcSize*DefaultPredictedCompressionRatio; using (StatusProcessor.Conditional(defDest, status, (long) predictedSize)) ret = ProcessManager.LaunchAndGrabTool(startInfo, "Gzip pack"); if (Path.GetFullPath(dest.ToString()) != Path.GetFullPath(defDest.ToString())) FileUtil.Ops.MoveWithRetry(defDest, dest); return ret.StandardOutput + ret.StandardError; }
async Task TryDownloadAsync(TransferSpec spec, IWebClient webClient, IAbsoluteFilePath tmpFile) { try { tmpFile.RemoveReadonlyWhenExists(); if (!string.IsNullOrWhiteSpace(spec.Uri.UserInfo)) { webClient.SetAuthInfo(spec.Uri); } using (webClient.HandleCancellationToken(spec)) await webClient.DownloadFileTaskAsync(spec.Uri, tmpFile.ToString()).ConfigureAwait(false); VerifyIfNeeded(spec, tmpFile); _fileOps.Move(tmpFile, spec.LocalFile); } catch (OperationCanceledException e) { _fileOps.DeleteIfExists(tmpFile.ToString()); throw CreateTimeoutException(spec, e); } catch (WebException ex) { _fileOps.DeleteIfExists(tmpFile.ToString()); var cancelledEx = ex.InnerException as OperationCanceledException; if (cancelledEx != null) { throw CreateTimeoutException(spec, cancelledEx); } if (ex.Status == WebExceptionStatus.RequestCanceled) { throw CreateTimeoutException(spec, ex); } var response = ex.Response as HttpWebResponse; if (response == null) { throw GenerateDownloadException(spec, ex); } switch (response.StatusCode) { case HttpStatusCode.NotFound: throw new RequestFailedException("Received a 404: NotFound response", ex); case HttpStatusCode.Forbidden: throw new RequestFailedException("Received a 403: Forbidden response", ex); case HttpStatusCode.Unauthorized: throw new RequestFailedException("Received a 401: Unauthorized response", ex); } throw GenerateDownloadException(spec, ex); } }
public YomaConfig(IAbsoluteFilePath inputAddonsFile, IAbsoluteFilePath inputModsFile, IAbsoluteFilePath inputServerFile = null) : this( XDocument.Load(inputAddonsFile.ToString()), XDocument.Load(inputModsFile.ToString()), inputServerFile == null ? null : XDocument.Load(inputServerFile.ToString())) { Contract.Requires<ArgumentOutOfRangeException>(inputAddonsFile != null); Contract.Requires<ArgumentOutOfRangeException>(inputModsFile != null); }
void CaseChangeMove(IAbsoluteFilePath source, IAbsoluteFilePath destination) { var tmpFile = source + GenericTools.TmpExtension; DeleteIfExists(tmpFile); File.Move(source.ToString(), tmpFile); File.Move(tmpFile, destination.ToString()); }
public static IEnumerable <string> GenerateCommandLineExecution(IAbsoluteFilePath location, string executable, params string[] desiredParams) { var updateExe = GetUpdateExe(location); return(updateExe != null && updateExe.Exists ? new[] { updateExe.ToString() }.Concat(Restarter.BuildUpdateExeArguments(executable, desiredParams)) : new[] { location.ToString() }.Concat(desiredParams)); }
public virtual void UnpackUpdater(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite = false, bool fullPath = true) { Contract.Requires<ArgumentNullException>(sourceFile != null); Contract.Requires<ArgumentNullException>(outputFolder != null); Generic.RunUpdater(UpdaterCommands.Unpack, sourceFile.ToString(), outputFolder.ToString(), overwrite ? "--overwrite" : null, fullPath.ToString()); }
public virtual string GzipAuto(IAbsoluteFilePath inputFile, IAbsoluteFilePath outputFile = null, bool preserveFileNameAndModificationTime = true, ITProgress status = null) { if (inputFile.ToString().EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) { return(GzipStdOut(inputFile, outputFile, preserveFileNameAndModificationTime, status)); } return(Gzip(inputFile, outputFile, preserveFileNameAndModificationTime, status)); }
public void PackTar(IAbsoluteDirectoryPath directory, IAbsoluteFilePath outputFile) { using (var tarStream = File.OpenWrite(outputFile.ToString())) using (var af = WriterFactory.Open(tarStream, ArchiveType.Tar, CompressionType.None)) { foreach (var f in directory.DirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) af.Write(f.FullName.Replace(directory.ParentDirectoryPath + @"\", ""), f.FullName); // This ommits the root folder ('userconfig') //af.WriteAll(directory.ToString(), "*", SearchOption.AllDirectories); } }
protected virtual void VerifyIfNeeded(TransferSpec spec, IAbsoluteFilePath localFile) { if ((spec.Verification == null) || spec.Verification(localFile)) { return; } Tools.FileUtil.Ops.DeleteFile(localFile); throw new VerificationError(localFile.ToString()); }
public void Copy(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite = true, bool checkMd5 = false) { if (FileUtil.ComparePathsEqualCase(source.ToString(), destination.ToString())) { throw new ArgumentException("Source and destination paths cannot be equal"); } if (checkMd5 && SumsAreEqual(source, destination)) { this.Logger() .Info("Source and destination files equal. Source: {0}, Destination: {1}", source, destination); return; } File.Copy(source.ToString(), destination.ToString(), overwrite); CopyTimestamps(source, destination); }
public void RunExtractPboWithParameters(IAbsoluteFilePath input, IAbsoluteDirectoryPath output, params string[] parameters) { if (!input.Exists) throw new IOException("File doesn't exist: " + input); var startInfo = new ProcessStartInfoBuilder(_extractPboBin, BuildParameters(input.ToString(), output.ToString(), parameters)).Build(); ProcessExitResult(_processManager.LaunchAndGrabTool(startInfo)); }
Timer UnlockTimer(IAbsoluteFilePath path, EventWaitHandle autoResetEvent) { var pathS = path.ToString(); if (!ShouldContinueChecking(autoResetEvent, pathS)) { return(null); } return(new TimerWithElapsedCancellation(1000, () => ShouldContinueChecking(autoResetEvent, pathS))); }
public ArchiveContent CreateFromExisting(IAbsoluteDirectoryPath destination, IAbsoluteFilePath file, IFileDownloader downloader) { var name = GetName(file.ToString()); var ac = new ArchiveContent(name, destination.ToString(), downloader); ac.ImportFromArchive(file); return(ac); }
public void CreateZip(IAbsoluteDirectoryPath directory, IAbsoluteFilePath outputFile) { using (var arc = ZipArchive.Create()) { foreach (var f in directory.DirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) arc.AddEntry(f.FullName.Replace(directory.ParentDirectoryPath + @"\", ""), f.FullName); arc.SaveTo(outputFile.ToString(), new ZipWriterOptions(CompressionType.Deflate) { DeflateCompressionLevel = CompressionLevel.BestCompression }); } }
static async Task CopyAsyncInternal(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite = true, ITProgress status = null) { using ( var sourceStream = File.Open(source.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read)) using (var destinationStream = File.Create(destination.ToString())) using (new StatusProcessor(destination, status, source.FileInfo.Length)) await sourceStream.CopyToAsync(destinationStream).ConfigureAwait(false); CopyTimestamps(source, destination); }
public BiKeyPair(IAbsoluteFilePath path) { Contract.Requires<ArgumentNullException>(path != null); Contract.Requires<ArgumentOutOfRangeException>(!path.FileName.Contains("@")); var p = path.ToString().Replace(".biprivatekey", String.Empty).Replace(".bikey", String.Empty); Location = Path.GetDirectoryName(p); Name = Path.GetFileName(p); CreatedAt = File.GetCreationTime(p); PrivateFile = (p + ".biprivatekey").ToAbsoluteFilePath(); PublicFile = (p + ".bikey").ToAbsoluteFilePath(); }
bool TryRunUpdater(IAbsoluteFilePath executable, params string[] parameters) { try { _processManager.StartAndForget(new ProcessStartInfo(executable.ToString(), parameters.CombineParameters())); return(true); } catch (Exception e) { this.Logger().FormattedErrorException(e); return(false); } }
private static string ReadHeader(IAbsoluteFilePath sourceFile) { if (!sourceFile.Exists) { return("$W6$: file does not exist"); } var buffer = new byte[1024]; using (var f = new FileStream(sourceFile.ToString(), FileMode.Open)) f.Read(buffer, 0, (int)Math.Min(f.Length, 1024)); return(GetString(buffer)); }
public void BaseAppIni() { if (inifiledata == null) { inifiledata = new FileIniDataParser(); var iniFilePath = strAlbumsINIFilePath.ToEnvVarFilePath(); iniFilePath.TryResolve(out IniAbsoluteFilePath); if (File.Exists(IniAbsoluteFilePath.ToString())) { inidata = inifiledata.ReadFile(IniAbsoluteFilePath.ToString()); } else { inifiledata.Parser.Configuration.CommentString = "#"; inidata = new IniData(); inifiledata.WriteFile(IniAbsoluteFilePath.ToString(), inidata); } } }
void MakeChecksum(Package package, IAbsoluteFilePath file, Dictionary <string, string> changeDictionary) { var f = file.ToString().Replace(package.WorkingPath + @"\", string.Empty).Replace(@"\", "/"); var status = new Status(f, package.StatusRepo) { Action = RepoStatus.Summing }; StatusDic[f] = status; changeDictionary.Add(f, package.Repository.GetChecksum(file)); status.EndOutput(); }
public void CreateTar(IAbsoluteDirectoryPath directory, IAbsoluteFilePath outputFile) { using (var tarStream = File.OpenWrite(outputFile.ToString())) using (var af = WriterFactory.Open(tarStream, ArchiveType.Tar, CompressionType.None)) { foreach (var f in directory.DirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) { af.Write(f.FullName.Replace(directory.ParentDirectoryPath + @"\", ""), f.FullName); } // This ommits the root folder ('userconfig') //af.WriteAll(directory.ToString(), "*", SearchOption.AllDirectories); } }
public void RunExtractPboWithParameters(IAbsoluteFilePath input, IAbsoluteDirectoryPath output, params string[] parameters) { if (!input.Exists) { throw new IOException("File doesn't exist: " + input); } var startInfo = new ProcessStartInfoBuilder(_extractPboBin, BuildParameters(input.ToString(), output.ToString(), parameters)).Build(); ProcessExitResult(_processManager.LaunchAndGrabTool(startInfo)); }
void ProcessFile(ProcessDirectoryOrFileParams spec, IAbsoluteFilePath filePath) { if (spec.OnlyWhenMissing && filePath.FileInfo.Directory.EnumerateFiles("*.bisign") .Any(s => MatchesBiSign(s.FullName, filePath.ToString()))) { return; } var biKeyPair = GetKey(spec, filePath.ParentDirectoryPath); _biSigner.SignFile(filePath, biKeyPair.PrivateFile, spec.RepackIfFailed); }
public ProcessExitResultWithOutput Run(ZsyncParams p) { TryHandleOldFiles(p.File); var startInfo = new ProcessStartInfo(_binPath.ToString(), GetArgs(p)) .SetWorkingDirectoryOrDefault(p.File.ParentDirectoryPath); var r = _processManager.LaunchAndGrab(new BasicLaunchInfo(startInfo)); if (r.ExitCode == 0) { TryRemoveOldFiles(p.File); } return(r); }
public static async Task <int> ExecuteAsync( NewFileOptions fileOptions, IConsole console, IAppEnvironment appEnvironment, InvocationContext context = null) { var settingsManager = new EnvironmentSettingsManager(appEnvironment); EnvironmentSettings environmentSettings = settingsManager.LoadSettings(); if (environmentSettings.WorkspacePath != null && fileOptions.FilePath != null) { console.Error.WriteLine("You must either set a workspace via the environment command or supply a filepath."); return(ReturnCodes.Error); } if (fileOptions.FilePath != null) { environmentSettings.WorkspacePath = fileOptions.FilePath.FullName; } List <ContentTypeConventionsRoot> conventions = await FindAllConventions(appEnvironment); // Select the convention that matches the template name specified ContentTypeConventionsRoot contentTypeConventionsRoot = conventions.FirstOrDefault(x => x.Conventions.Any(y => y.Conventions.Any(z => z.Value == fileOptions.TemplateName))); // Now find the filepath.. Convention convention = contentTypeConventionsRoot?.Conventions.SelectMany(x => x.Conventions).FirstOrDefault(x => x.ContentType.StartsWith(ConventionContentTypes.FilePaths, StringComparison.CurrentCultureIgnoreCase)); if (convention != null) { IVariableDirectoryPath variablePath = convention.Value.ToVariableDirectoryPath(); if (variablePath.TryResolve(environmentSettings.ToKvPs(), out IAbsoluteDirectoryPath evaluatedPath) == VariablePathResolvingStatus.Success) { IAbsoluteFilePath filepath = evaluatedPath.GetChildFileWithName($"post-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.md"); if (!filepath.ParentDirectoryPath.Exists) { Directory.CreateDirectory(filepath.ParentDirectoryPath.ToString()); } string template = Path.Join(contentTypeConventionsRoot.FilePath.ParentDirectoryPath.ParentDirectoryPath.ToString(), contentTypeConventionsRoot?.Conventions.FirstOrDefault()?.TemplatePath); File.Copy(template, filepath.ToString()); console.Out.WriteLine($"Created: {filepath}"); } } return(ReturnCodes.Ok); }
async Task TryDownloadAsync(TransferSpec spec, IWebClient webClient, IAbsoluteFilePath tmpFile) { try { tmpFile.RemoveReadonlyWhenExists(); if (!string.IsNullOrWhiteSpace(spec.Uri.UserInfo)) webClient.SetAuthInfo(spec.Uri); using (webClient.HandleCancellationToken(spec)) await webClient.DownloadFileTaskAsync(spec.Uri, tmpFile.ToString()).ConfigureAwait(false); VerifyIfNeeded(spec, tmpFile); _fileOps.Move(tmpFile, spec.LocalFile); } catch (OperationCanceledException e) { _fileOps.DeleteIfExists(tmpFile.ToString()); throw CreateTimeoutException(spec, e); } catch (WebException e) { _fileOps.DeleteIfExists(tmpFile.ToString()); var cancelledEx = e.InnerException as OperationCanceledException; if (cancelledEx != null) throw CreateTimeoutException(spec, cancelledEx); if (e.Status == WebExceptionStatus.RequestCanceled) throw CreateTimeoutException(spec, e); GenerateDownloadException(spec, e); } }
public void UnpackGzip(IAbsoluteFilePath sourceFile, IAbsoluteFilePath destFile, ITProgress progress = null) { using (var archive = GZipArchive.Open(sourceFile.ToString())) { try { TryUnpackArchive(destFile, progress, archive); } catch (ZlibException ex) { if ((ex.Message == "Not a valid GZIP stream.") || (ex.Message == "Bad GZIP header.") || (ex.Message == "Unexpected end-of-file reading GZIP header.") || (ex.Message == "Unexpected EOF reading GZIP header.")) { var header = TryReadHeader(sourceFile); throw new CompressedFileException( $"The archive appears corrupt: {sourceFile}. Header:\n{header}", ex); } throw; } } }
public virtual void Unpack(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite = false, bool fullPath = true, bool force7z = false, bool checkFileIntegrity = true, ITProgress progress = null) { Contract.Requires<ArgumentNullException>(sourceFile != null); Contract.Requires<ArgumentNullException>(outputFolder != null); var ext = sourceFile.FileExtension; if (force7z || SevenzipArchiveFormats.Any(x => ext.Equals(x, StringComparison.OrdinalIgnoreCase))) { using (var extracter = new SevenZipExtractor(sourceFile.ToString())) UnpackArchive(sourceFile, outputFolder, overwrite, checkFileIntegrity, extracter); } else { var options = fullPath ? ExtractOptions.ExtractFullPath : ExtractOptions.None; using (var archive = GetArchiveWithGzWorkaround(sourceFile, ext)) UnpackArchive(outputFolder, overwrite, archive, options); } }
static bool InstallDll(IAbsoluteFilePath pluginPath, IAbsoluteDirectoryPath gamePluginFolder, bool force = true) { Contract.Requires<ArgumentNullException>(gamePluginFolder != null); Contract.Requires<ArgumentNullException>(pluginPath != null); if (!pluginPath.IsNotNullAndExists()) throw new PathDoesntExistException(pluginPath.ToString()); if (!gamePluginFolder.IsNotNullAndExists()) throw new PathDoesntExistException(gamePluginFolder.ToString()); var fullPath = gamePluginFolder.GetChildFileWithName(pluginPath.FileName); if (!force && fullPath.Exists) return false; return TryCopyDll(pluginPath, fullPath); }
Timer UnlockTimer(IAbsoluteFilePath path, EventWaitHandle autoResetEvent) { var timer = new Timer(); var pathS = path.ToString(); timer.Elapsed += delegate { lock (timer) { if (timer.Enabled) { var unlocked = CheckFileClosed(pathS); if (unlocked) { // disable timer as soon as file is unlocked, to raise event only once! timer.Enabled = false; autoResetEvent.Set(); } // set interval to 1 second after first elapse timer.Interval = 1000; } } }; return timer; }
internal static ControlFile Create(IAbsoluteFilePath controlFile) { var @this = new ControlFile(); var lines = new Queue<string>(File.ReadAllLines(controlFile.ToString())); @this.Version = GetValue("zsync", lines.Dequeue()); @this.Filename = GetValue("Filename", lines.Dequeue()); @this.MTime = GetValue("MTime", lines.Dequeue()); @this.Blocksize = Convert.ToInt32(GetValue("Blocksize", lines.Dequeue())); @this.Length = Convert.ToInt64(GetValue("Length", lines.Dequeue())); @this.HashLengths = GetValue("Hash-Lengths", lines.Dequeue()).Split(',').Select(int.Parse).ToList(); @this.Url = GetValue("URL", lines.Dequeue()); @this.Sha1 = GetValue("SHA-1", lines.Dequeue()); if(lines.Dequeue() != "") throw new ControlFileParseException("Expected End of Headers"); return @this; }
public static async Task DownloadAsync(this HttpClient httpClient, Uri requestUri, IAbsoluteFilePath filename) { if (filename == null) throw new ArgumentNullException("filename"); /* if (Proxy != null) { WebRequest.DefaultWebProxy = Proxy; }*/ using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri)) using ( var contentStream = await (await httpClient.SendAsync(request).ConfigureAwait(false)).Content.ReadAsStreamAsync() .ConfigureAwait(false)) using ( Stream stream = new FileStream(filename.ToString(), FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) await contentStream.CopyToAsync(stream).ConfigureAwait(false); }
public void UnpackSingleGzip(IAbsoluteFilePath sourceFile, IAbsoluteFilePath destFile, ITProgress progress = null) { using (var archive = GZipArchive.Open(sourceFile.ToString())) { if (progress != null) { archive.CompressedBytesRead += (sender, args) => { double prog = (args.CompressedBytesRead/(float) archive.TotalSize); if (prog > 1) prog = 1; progress.Progress = prog*100; }; } destFile.RemoveReadonlyWhenExists(); var entry = archive.Entries.First(); entry.WriteToFile(destFile.ToString()); } }
public virtual string GzipAuto(IAbsoluteFilePath inputFile, IAbsoluteFilePath outputFile = null, bool preserveFileNameAndModificationTime = false) { if (inputFile.ToString().EndsWith(".gz", StringComparison.InvariantCultureIgnoreCase)) return GzipStdOut(inputFile, outputFile, preserveFileNameAndModificationTime); return Gzip(inputFile, outputFile, preserveFileNameAndModificationTime); }
static void HandleBackupRepositoryFile(IAbsoluteFilePath repFile, IAbsoluteFilePath bkpFile) { if (repFile.Exists) Tools.FileUtil.Ops.CopyWithRetry(repFile, bkpFile); else if (bkpFile.Exists) Tools.FileUtil.Ops.DeleteWithRetry(bkpFile.ToString()); }
static void UnpackSingleZipWithUpdaters(IAbsoluteFilePath sourceFile, IAbsoluteFilePath destFile) { Generic.RunUpdater(UpdaterCommands.UnpackSingleGzip, sourceFile.ToString(), destFile.ToString()); }
static string GetChecksum(IAbsoluteFilePath uconfigPath) { using (var md5 = MD5.Create()) using (var stream = File.OpenRead(uconfigPath.ToString())) return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); }
void ProcessFile(ProcessDirectoryOrFileParams spec, IAbsoluteFilePath filePath) { if (spec.OnlyWhenMissing && filePath.FileInfo.Directory.EnumerateFiles("*.bisign") .Any(s => MatchesBiSign(s.FullName, filePath.ToString()))) return; var biKeyPair = GetKey(spec, filePath.ParentDirectoryPath); _biSigner.SignFile(filePath, biKeyPair.PrivateFile, spec.RepackIfFailed); }
public void WriteClass(IAbsoluteFilePath input, IAbsoluteFilePath output) { File.WriteAllText(output.ToString(), Convert(input)); }
ProcessExitResult InstallPatch(IAbsoluteFilePath filePath, string parameters) => _processManager.Launch(new BasicLaunchInfo(new ProcessStartInfo(filePath.ToString(), parameters)));
public Version GetVersion(IAbsoluteFilePath exePath) { Contract.Requires<ArgumentNullException>(exePath != null); if (!exePath.Exists) return null; return FileVersionInfo.GetVersionInfo(exePath.ToString()).ProductVersion.TryParseVersion(); }