public void GetDirectoryStack_ValidDirectory_ValidDirectoryStack() { string executingDir = Directory.GetCurrentDirectory(); Stack <DirectoryInfo> stack = IoHelper.GetDirectoryStack(executingDir); Assert.IsTrue(stack.Count > 0); }
public void GetFiles_ValidPath_ArrayOfFiles() { string path = GetExecutingAssemblyFolder(); string[] files = IoHelper.GetFiles(path); Assert.IsTrue(files.Length > 0); }
public void DeleteFiles_ValidLocation_DeletesAllFilesFiltered() { string path = Path.Combine(GetExecutingAssemblyFolder(), "TestLocation"); Directory.CreateDirectory(path); for (int i = 0; i < 10; i++) { string file = Path.Combine(path, Path.GetFileName(Path.GetTempFileName())); File.WriteAllText(file, RandomString.NextAlphabet(100)); } string file2 = Path.Combine(path, "temp.txt"); File.WriteAllText(file2, RandomString.NextAlphabet(100)); string file3 = Path.Combine(path, "temp2.txt"); File.WriteAllText(file3, RandomString.NextAlphabet(100)); int currentCount = Directory.EnumerateFiles(path).Count(); IoHelper.DeleteFiles(path, "*.txt"); int afterDelCount = Directory.EnumerateFiles(path).Count(); Assert.IsTrue(currentCount - afterDelCount == 2); Directory.Delete(path, true); }
public static void EncryptPgpFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck) { using (Stream publicKeyStream = File.OpenRead(publicKeyFile)) { PgpPublicKey pubKey = ReadPublicKey(publicKeyStream); using (MemoryStream outputBytes = new MemoryStream()) { PgpCompressedDataGenerator dataCompressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); PgpUtilities.WriteFileToLiteralData(dataCompressor.Open(outputBytes), PgpLiteralData.Binary, new FileInfo(inputFile)); dataCompressor.Close(); PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); dataGenerator.AddMethod(pubKey); byte[] dataBytes = outputBytes.ToArray(); using (Stream outputStream = File.Create(outputFile)) { if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream)) { IoHelper.WriteStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes); } } else { IoHelper.WriteStream(dataGenerator.Open(outputStream, dataBytes.Length), ref dataBytes); } } } } }
/// <summary> /// Log the specified message to <see cref="FilePath"/> /// </summary> /// <param name="message">Message to log</param> public void Log(string message) { IoHelper.TryCreateDirectoryIfNotExists(IoHelper.LocalAppDataPath); IoHelper.TryAppendToFile(FilePath, $"[{DateTime.Now.ToString(DateFormatString)}]: {message}\n"); }
private void AddImagesFromDirectory(DirectoryInfo dir) { if (!_isCurrentlyLoading) { return; } try { foreach (var currFile in _fileEnumerator.EnumerateFiles(dir)) { if (!_isCurrentlyLoading) { return; } var fileName = currFile.FullName; if (IoHelper.IsValidImageFile(fileName)) { _dispatcher.Dispatch(() => Model.AllImages.Add(new SelectableImage { FullPath = fileName, IsSelected = false })); } } foreach (var currSubDir in _fileEnumerator.EnumerateDirectories(dir)) { AddImagesFromDirectory(currSubDir); } } catch (Exception ex) { _warnings.Add(ex.Message); } }
/// <summary> /// /// </summary> /// <returns></returns> public bool BulkCopy(MonetBulkCopyModel model) { try { var connectionString = model.ToString(); var stopWatch = new Stopwatch(); var data = model.Rows.Lz4Decompress().ToStrings(); var fileName = IoHelper.GetTmpRandomFileName(_serverConfiguration.TempDir); stopWatch.Start(); MonetDbHelper.DumpBinary(data, fileName); if (IoHelper.IsNotEmpty(fileName)) { MonetDbHelper.BinaryCopy(connectionString, model.SchemaName, model.TableName, data.Length, fileName); } IoHelper.RemoveFile(fileName); stopWatch.Stop(); LoggerHelper.Write(LoggerOption.Info, "Client#{0} -> Loaded '{1}.{2}.{3}'-{4} rows({5} ms)", CurrentClient.ClientId, model.Database, model.SchemaName, model.TableName, data.Length, stopWatch.ElapsedMilliseconds); return(true); } catch (Exception exception) { LoggerHelper.Write(LoggerOption.Error, exception.Message); throw; } }
public void GetDynamicStorePathValuesTest( [Range(1, 2)] long datasetId, [Range(1, 2)] long datasetVersionOrderNr) { string path = IoHelper.GetDynamicStorePath(datasetId, datasetVersionOrderNr, "title", ".txt"); path.Should().NotBeNull("Because path is not null."); }
/// <summary> /// Loads the localization collections /// </summary> /// <returns></returns> public List <LocalizationCollection> LoadLocalizationCollections() { var result = new List <LocalizationCollection>(); foreach (var source in GetLocalizationSourcesPaths()) { var files = IoHelper.SearchFiles(source.Value, LocalizationSearchRegex + Configuration.FileExtension); foreach (var file in files) { // Get the filename from the file var fileName = IoHelper.GetFileNameFromPath(file); // Get the match from the filename var match = fileName.GetMatch(LocalizationMatchingRegex + Configuration.FileExtension); var category = GetLocalizationCategoryByName(IoHelper.GetFileFolder(file)); result.Add(new LocalizationCollection { Name = match.Groups["FILENAME"].Value, LocalizationCategory = category }); } } return(result); }
private static void CloseConnectionToServer(Socket a_Socket) { string messageToSend = Protocol.GetClientMessageXmlStr(Protocol.ClientMessage.Complete); IoHelper.SendMessage(a_Socket, messageToSend); a_Socket.Close(); }
public string CreateZipFromSettings(string json) { try { // TODO: Что делать, если папки, указанные в настройках, отсутствуют фактически? var availableBrands = ResourceManager.AvailableBrands(json).Select(path => new DirectoryInfo(Path.Combine(ResourceManager.Root, path))); var tempFolder = ClearTempFolder(); var subdirectory = tempFolder.CreateSubdirectory(Guid.NewGuid().ToString()); foreach (var brand in availableBrands) { IoHelper.DirectoryCopy(brand.FullName, Path.Combine(subdirectory.FullName, brand.Name), true); } var archiveFileName = Path.Combine(tempFolder.FullName, string.Format("{0}.zip", subdirectory.Name)); ZipFile.CreateFromDirectory(subdirectory.FullName, archiveFileName); return(archiveFileName); } catch (Exception ex) { eventHandler.ProcessException(ex); return(null); } }
public void ApplyImage_ShouldApplyPartOfImage() { var partOfImage = FluentImage.FromFile(IoHelper.ResolveUrl("Montanhas azuis.jpg")); partOfImage.Resize.Crop(new Rectangle(100, 0, 200, partOfImage.Current.Height)); this.image.Draw.ApplyImage(partOfImage); }
protected async Task GenerateFilesAsync(List <ImageInformation> parameters) { Context.Log($" - {this.GeneratorName} "); using (var progress = Context.ProgressVisualizerFactory.Create()) { for (var index = 0; index < parameters.Count; index++) { progress.Report((float)index / parameters.Count); var parameter = parameters[index]; if (Context.Options.SkipExisting && File.Exists(parameter.DestinationPath)) { continue; } IoHelper.CreateDirectoryRecursive(Path.GetDirectoryName(parameter.DestinationPath)); foreach (var extension in Context.Options.FileExtensions) { if (TryGetImageFormat(extension.ToLowerInvariant(), out ImageFormat format)) { var destinationFolder = Path.GetDirectoryName(parameter.DestinationPath); var fnWithoutEx = Path.GetFileNameWithoutExtension(parameter.DestinationPath); await ConvertImageAsync(parameter.SourcePath, Path.Combine(destinationFolder, $"{fnWithoutEx}{extension}"), parameter.WidthDp, parameter.HeightDp, parameter.Dpi, format, parameter.Color).ConfigureAwait(false); } } } } Context.Log(Environment.NewLine); }
private static void RunUserProfileExport() { var io = new IoHelper(DirEventsAll, DirMicroCommits); var helper = new UserProfileExportHelper(); new UserProfileExportRunner(io, helper).Export(DirEventsAll); }
private void proxyBtn_Click(object sender, EventArgs e) { Config.ProxyBufferList.Clear(); IoHelper.OpenFileDialog(ref Config.ProxyList); proxyLbl.Text = Statistic.ProxyCount.ToString(CultureInfo.InvariantCulture); IoHelper.WriteBlock(Config.ProxyList, "proxy.txt"); }
public bool Run(string inputFile, string outputFile, out List <TerminalMessage> messages) { messages = new List <TerminalMessage>(); EnvironmentPath = IoHelper.GetEnvironmentPath(); ResultingFileContent = File.ReadAllText(inputFile); OperatedFile = inputFile; var regex = new Regex(@"/\*\*(jsmrg)(?:(?!\*/).)*\*/", RegexOptions.Singleline); var matches = regex.Matches(ResultingFileContent); var operationResult = OperateMatches(messages, matches); messages = operationResult.Messages; if (operationResult.IsOk) { if (IoHelper.WriteOutputFile(outputFile, ResultingFileContent)) { messages.Add(TerminalMessage.Create($"JsMrg successful.", Color.DarkGreen)); messages.Add(TerminalMessage.LineBreak()); } else { messages.Add(TerminalMessage.Create($"JsMrg complete, but failed to write output file {outputFile}.", Color.Red)); // Last operation failed, so overwrite IsOk: operationResult.IsOk = false; } } return(operationResult.IsOk); }
/// <summary> /// Reads the addin metadata from the addin storage file /// </summary> /// <returns></returns> internal bool ReadOrReset() { if (!File.Exists(_storageFilePath)) { return(false); } FileStream stream = null; try { // open the addin storage file with readonly mode. stream = IoHelper.OpenReadWrite(_storageFilePath); var result = DoRead(stream); if (stream != null) { stream.Dispose(); } if (!result) { IoHelper.ClearContent(_storageFilePath); } return(result); } catch (Exception ex) { if (stream != null) { stream.Dispose(); IoHelper.ClearContent(_storageFilePath); } return(false); } }
private void DisplayProgressThread(Object obj) { ListViewItem newLvi = (ListViewItem)obj; UpdateFile si = (UpdateFile)newLvi.Tag; long lastPos = 0; DateTime lastTime = DateTime.Now; while (si.DownloadPercent != 1) { if (si.Length > 0) { double seconds = (DateTime.Now - lastTime).TotalSeconds; if (seconds == 0.0) { continue; } long bytes = Convert.ToInt64((si.DownloadPercent * si.Length)) - lastPos; long speed = Convert.ToInt64(bytes / seconds); si.Status = String.Format("{0}/s", IoHelper.getFileLengthLevel(speed, 1)); } lastTime = DateTime.Now; lastPos = Convert.ToInt64((si.DownloadPercent * si.Length)); InvalidateListViewItem(newLvi); Thread.Sleep(1000); } si.Status = "完成"; InvalidateListViewItem(newLvi); }
/// <summary> /// Get path of the current running assemlby /// </summary> /// <returns></returns> public static string GetCurrentAssemblyRunPath() { var filePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; var pathWithExcludedFilename = IoHelper.GetPathWithoutFileName(filePath); return(pathWithExcludedFilename); }
private void AddImagesFromDirectory(DirectoryInfo dir) { try { foreach (var currFile in _fileEnumerator.EnumerateFiles(dir)) { var fileName = currFile.FullName; if (IoHelper.IsValidImageFile(fileName)) { _dispatcher.Dispatch(() => Model.PhotoFiles.Add(fileName)); if (HasEnoughFiles) { return; } } } if (!HasEnoughFiles) { foreach (var currSubDir in _fileEnumerator.EnumerateDirectories(dir)) { AddImagesFromDirectory(currSubDir); if (HasEnoughFiles) { return; } } } } catch (Exception ex) { _warnings.Add(ex.Message); } }
protected override void Add() { HoldingViewModel holding = new HoldingViewModel(new HoldingModel { Name = "New", IpServer = "localhost", Nom = Holdings.Count + 1 }); var conf = ConfigTempoSinglenton.GetInstance(); holding.ConnectionString = string.Format(Entrence.ConectionStringTemplate, holding.IpServer, conf.BaseDbPath, "H" + holding.Nom); Holdings.Add(holding); if ( MessageBoxWrapper.Show("Копиране на празна база от темплейтите?", "Предупреждение", MessageBoxWrapperButton.YesNo) == MessageBoxWrapperResult.Yes) { IoHelper.DirectoryCopy(ConfigTempoSinglenton.GetInstance().BaseTemplatePath, Path.Combine(ConfigTempoSinglenton.GetInstance().BaseDbPath, "H" + holding.Nom), true); } foreach (var item in conf.ConfigNames) { var spliter = item.Split('|'); FirmSettingModel newsett = new FirmSettingModel(); newsett.Key = spliter[0]; newsett.Name = spliter[1]; newsett.Value = spliter[2]; newsett.FirmaId = 1; newsett.HoldingId = holding.Nom; conf.FirmSettings.Add(newsett); } conf.SaveConfiguration(); }
// public abstract IConfiguration GetTemplate(); public void Save() { string path = Path.Combine(ConfigPath, GetType().FullName + ".json"); IoHelper.EnsureFileAndPath(path); File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); }
private static void Main(string[] args) { const double maxAmplitude = 1000; double coefLong = 36; // I want my sine function to have period of 36 units double coefShort = 13; // I want my sine function to have period of 7 units double degreeCoefLong = 360 / coefLong; double degreeCoefShort = 360 / coefShort; double halfAmplitude = maxAmplitude / 2; double quarterAmplitude = maxAmplitude / 4; // The code provided will print ‘Hello World’ to the console. // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app. Console.WriteLine("MathTest Console"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); // Open csv file IoHelper.CreateDirectory(path); var fullFilePath = path + baseFileName + XDateTime.NowToFileSuffix() + fileExt; TextFileHelper.OpenTextFileForWrite(fullFilePath, false); // Write header TextFileHelper.AppendLine("Degrees," + "Sin," + "Sin+1," + "Amplified Sin + 1," + "Amplified SinShort + 1," + "Amplified SinLong + 1," + "Mixed," ); for (int degree = 0; degree < 720; degree++) { var sin = Math.Sin(degree * Math.PI / 180); var sinShort = Math.Sin(degreeCoefShort * degree * Math.PI / 180); var sinLong = Math.Sin(degreeCoefLong * degree * Math.PI / 180); //Console.WriteLine($"{degree}°: Sin={sin:f4}"); // write data to CSV file TextFileHelper.AppendLine($"{degree}," + $"{sin}," + $"{sin+1}," + $"{halfAmplitude * (sin + 1)}," + $"{halfAmplitude * (sinShort + 1)}," + $"{halfAmplitude * (sinLong + 1)}," + $"{quarterAmplitude * (sinShort + sinLong + 2)}," ); } TextFileHelper.CloseWriteTextFile(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press any key ..."); //Console.ReadKey(); GlobalHelper.ProcessStart(fullFilePath); }
public IActionResult Index( ) { ViewBag.AdditionalInfo = "Additional information"; var filePath = Path.Combine(_appEnvironment.ApplicationBasePath, "css", "site.css"); var content = IoHelper.ReadFile(filePath); return(View( )); }
static bool IsScannableManifestFile(string file, AddinFilePack matchingFilePack) { var fi = IoHelper.GetFileInfo(file); return(fi.Length != matchingFilePack.ManifestFile.FileLength || fi.LastWriteTime != matchingFilePack.ManifestFile.LastWriteTime || IoHelper.GetFileHash(file) != matchingFilePack.ManifestFile.FileHash); }
public void SetUp() { destImageStream = IoHelper.ResolveUrl("Inverno_NEW_stream.jpg"); destImageFile = IoHelper.ResolveUrl("Inverno_NEW.jpg"); DeleteIfExists(destImageStream); DeleteIfExists(destImageFile); }
public void GetFileInfo_InValidPath_Throws() { string path = GetExecutingAssemblyFolder(); var fileInfoList = IoHelper.GetFileInfoCollection(path); Assert.IsTrue(fileInfoList.Count() > 0); }
public TokenisedPackageBuilder( ManifestBuilder manifestBuilder, FileContentHelper fileContentProcessor, AppConfiguration appConfiguration, IoHelper ioHelper) { this.manifestBuilder = manifestBuilder; this.fileContentProcessor = fileContentProcessor; this.appConfiguration = appConfiguration; this.ioHelper = ioHelper; }
public void BuildFileShareSafeStreamWriter_InvalidDir_ThrowsArgumentException() { string testFile = Path.Combine(Directory.GetCurrentDirectory(), "UnitTesting", "TESTFILE.txt"); Directory.CreateDirectory(Path.GetDirectoryName(testFile)); Directory.Delete(Path.GetDirectoryName(testFile), true); Assert.Throws <ArgumentException>(() => IoHelper.BuildFileShareSafeStreamWriter(testFile)); }
private void PushNewUpdateFile(UpdateFile newFile) { ListViewItem newLvi = lvSelectUpdate.Items.Add(newFile.FileName); newLvi.SubItems.Add(newFile.FileVersion.ToString()); newLvi.SubItems.Add(IoHelper.getFileLengthLevel(newFile.Length, 2)); newLvi.Tag = newFile; newLvi.Checked = true; }