public void TestNewerFileNotOverwritten() { // Arrange ILoggerFactory loggerFactory = new LoggerFactory(); ILogger logger = loggerFactory.CreateConsoleLogger(); var mockFileDataMap = new Dictionary <string, MockFileData>() { { @"C:\myfile.txt", new MockFileData("Old data") }, { @"D:\myfile.txt", new MockFileData("New data") } }; IFileSystem mockFileSystem = new MockFileSystem(mockFileDataMap); FileInfoBase oldFileInfo = mockFileSystem.FileInfo.FromFileName(@"C:\myfile.txt"); oldFileInfo.LastWriteTimeUtc = DateTime.UtcNow; FileInfoBase newFileInfo = mockFileSystem.FileInfo.FromFileName(@"D:\myfile.txt"); newFileInfo.LastWriteTimeUtc = DateTime.UtcNow + new TimeSpan(0, 0, 0, 1); var application = new DriveBackup.Application(mockFileSystem, logger); // Act application.Run(@"C:\", @"D:\"); // Assert Assert.IsTrue(mockFileSystem.File.Exists(@"D:\myfile.txt")); Assert.AreNotEqual( mockFileSystem.FileInfo.FromFileName(@"C:\myfile.txt").LastWriteTimeUtc, mockFileSystem.FileInfo.FromFileName(@"D:\myfile.txt").LastWriteTimeUtc ); Assert.AreNotEqual( mockFileSystem.File.ReadAllText(@"C:\myfile.txt"), mockFileSystem.File.ReadAllText(@"D:\myfile.txt") ); }
private string SafeReadContents(string file, out FileInfoBase fileInfo) { try { fileInfo = this._fileSystem.FileInfo.FromFileName(file); return(this._fileSystem.File.ReadAllText(file)); } catch (IOException) { fileInfo = this._fileSystem.FileInfo.FromFileName(file); var tempFile = Path.Combine(Path.GetTempPath(), fileInfo.Name); try { fileInfo.CopyTo(tempFile, true); return(this._fileSystem.File.ReadAllText(tempFile)); } finally { if (this._fileSystem.File.Exists(tempFile)) { this._fileSystem.File.Delete(tempFile); } } } }
public static bool IsFirstFileNewer(this IFileSystem fileSystem, string sourcePath, string destinationPath) { FileInfoBase sourceFileInfo = fileSystem.FileInfo.FromFileName(sourcePath); FileInfoBase destinationFileInfo = fileSystem.FileInfo.FromFileName(destinationPath); return(sourceFileInfo.LastWriteTime > destinationFileInfo.LastWriteTime); }
public static void Extract(this ZipArchive archive, string directoryName, ITracer tracer, bool doNotPreserveFileTime = false) { const int MaxExtractTraces = 5; var entries = archive.Entries; var total = entries.Count; var traces = 0; using (tracer.Step(string.Format("Extracting {0} entries to {1} directory", entries.Count, directoryName))) { foreach (ZipArchiveEntry entry in entries) { string path = Path.Combine(directoryName, entry.FullName); if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal))) { // Extract directory FileSystemHelpers.CreateDirectory(path); } else { FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path); string message = null; // tracing first/last N files if (traces < MaxExtractTraces || traces >= total - MaxExtractTraces) { message = string.Format("Extracting to {0} ...", fileInfo.FullName); } else if (traces == MaxExtractTraces) { message = "Omitting extracting file traces ..."; } ++traces; using (!string.IsNullOrEmpty(message) ? tracer.Step(message) : null) { if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } using (Stream zipStream = entry.Open(), fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write)) { zipStream.CopyTo(fileStream); } // this is to allow, the file time to always be newer than destination // the outcome is always replacing the destination files. // it is non-optimized but workaround NPM reset file time issue (https://github.com/projectkudu/kudu/issues/2917). if (!doNotPreserveFileTime) { fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime; } } } } } }
public static void AddFile(this ZipArchive zipArchive, FileInfoBase file, string prefix, string directoryNameInArchive) { Stream fileStream = null; try { fileStream = file.OpenRead(); } catch (Exception ex) { // tolerate if file in use. // for simplicity, any exception. //tracer.TraceError(String.Format("{0}, {1}", file.FullName, ex)); return; } try { string fileName = ForwardSlashCombine(directoryNameInArchive, file.Name); ZipArchiveEntry entry = zipArchive.CreateEntry(String.Concat(prefix, fileName), CompressionLevel.Fastest); entry.LastWriteTime = file.LastWriteTime; using (Stream zipStream = entry.Open()) { fileStream.CopyTo(zipStream); } } finally { fileStream.Dispose(); } }
public ResumableLogFileReader(FileInfoBase fileInfo, ITracer tracer, LogFileAccessStats stats = null) { _stats = stats; _tracer = tracer; _lines = CreateReverseLineReader(fileInfo); LastTime = fileInfo.LastWriteTimeUtc; }
public void ExtractSnippet() { // Declare content const string content = @"Some Content Here"; // Mock file system IFileSystem fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { "Content.txt", new MockFileData(content) } }); // Run the extraction DefaultSnippetExtractor extractor = new DefaultSnippetExtractor(); FileInfoBase fileInfoBase = fileSystem.FileInfo.FromFileName("Content.txt"); Extension.Model.PlainTextSnippet snippet = extractor.Extract(fileInfoBase, null) as Extension.Model.PlainTextSnippet; // Load the expected file content MemoryStream memoryStream = new MemoryStream(); using (var fileReader = new StreamReader(fileInfoBase.OpenRead())) using (var fileWriter = new StreamWriter(memoryStream)) { fileWriter.Write(fileReader.ReadToEnd()); } // Assert Assert.AreEqual(content, snippet.Text); }
public SpecRunSingleResults(FileInfoBase fileInfo) { var resultsDocument = this.ReadResultsFile(fileInfo); this.specRunFeatures = resultsDocument.Descendants("feature").Select(SpecRun.Factory.ToSpecRunFeature).ToList(); }
public void TrimToGivenLength() { // arrange var creationTime = DateTime.Now.AddHours(-4); string myFileName = "1c4b311d47205c46951385c440c80bf12008ed1459b5d0d2b2bd1ec18a102d4e"; string myPath = Path.Combine("C:\\Users\\PGullas\\Pictures\\downloaded lock screens\\download-test", myFileName); byte[] fileContentsBase64 = Encoding.ASCII.GetBytes("iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAE0lEQVR42mP8z8BQz4AEGEkXAADyrgX9UgHC3gAAAABJRU5ErkJggg=="); string expectedName = "c18a102d4e"; var fileData = new MockFileData(fileContentsBase64) { CreationTime = creationTime }; var fs = new MockFileSystem(new Dictionary <string, MockFileData> { { myPath, fileData } }); FileInfoBase fi = fs.FileInfo.FromFileName(myPath); LockScreenImageToLog ls = new LockScreenImageToLog(fi, fs); // act string nameToTest = ls.GetFilenameTrimmedDownToLast(10); // assert Assert.AreEqual(expectedName, nameToTest); }
public void AddNewExtensionCorrectly() { // Arrange string myFileName = "ec18a102d4e"; string myPath = Path.Combine("C:\\Users\\PGullas\\Pictures\\downloaded lock screens\\download-test", myFileName); byte[] fileContentsBase64 = Encoding.ASCII.GetBytes("iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAE0lEQVR42mP8z8BQz4AEGEkXAADyrgX9UgHC3gAAAABJRU5ErkJggg=="); string expectedName = "ec18a102d4e.jpg"; var creationTime = DateTime.Now.AddHours(-4); var fileData = new MockFileData(fileContentsBase64) { CreationTime = creationTime }; var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { myPath, fileData } }); FileInfoBase fi = fileSystem.FileInfo.FromFileName(myPath); LockScreenImageToLog ls = new LockScreenImageToLog(fi, fileSystem); // Act string nameToTest = ls.GetFilenameWithNewExtension(); // Assert Assert.AreEqual(expectedName, nameToTest); }
public void FileInfoBase_CopyTo_ShouldKeepLengthOnCopy() { // Arrange var fs = new MockFileSystem(); // need to add trailing slash to a mock foldername, otherwise it gives us "Could not find a part of the path" string folder1 = @"c:\folder1"; string folder2 = @"c:\folder2"; fs.AddDirectory(folder1); fs.AddDirectory(folder2); var creationTime = DateTime.Now.AddHours(-4); byte[] fileContentsBase64 = Encoding.ASCII.GetBytes("iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAE0lEQVR42mP8z8BQz4AEGEkXAADyrgX9UgHC3gAAAABJRU5ErkJggg=="); var fileToCopy = new MockFileData(fileContentsBase64) { CreationTime = creationTime }; string filename1 = @"testfile01.jpg"; string filePath1 = fs.Path.Combine(folder1, filename1); fs.AddFile(filePath1, fileToCopy); FileInfoBase fi = fs.FileInfo.FromFileName(filePath1); string filename2 = @"copyfile02.jpg"; string filePath2 = fs.Path.Combine(folder2, filename2); // Act fi.CopyTo(filePath2); FileInfoBase fi2 = new FileInfo(filePath2); // Assert Assert.AreEqual(fi.Length, fi2.Length); }
private IEnumerable <string> CreateReverseLineReader(FileInfoBase fileInfo) { return(new MiscUtil.IO.ReverseLineReader(() => { try { var stream = FileSystemHelpers.OpenFile(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (_stats != null) { _stats.IncrementOpenReadCount(fileInfo.Name); } return stream; } catch (UnauthorizedAccessException e) { // If we are unable to open the file, silently skip it this time _tracer.TraceError(e); return Stream.Null; } catch (IOException e) { _tracer.TraceError(e); return Stream.Null; } })); }
public SingleTestRunBase Load(FileInfoBase fileInfo) { var document = this.ReadResultsFile(fileInfo); var features = this.ToFeatures(document); return(new SpecRunSingleResults(features)); }
private void CleanupLogFileIfNeeded() { try { FileInfoBase logFile = FileSystemHelpers.FileInfoFromFileName(_logFilePath); if (logFile.Length > MaxContinuousLogFileSize) { // lock file and only allow deleting it // this is for allowing only the first (instance) trying to roll the log file using (File.Open(_logFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete)) { // roll log file, currently allow only 2 log files to exist at the same time string prevLogFilePath = GetLogFilePath(JobPrevLogFileName); FileSystemHelpers.DeleteFileSafe(prevLogFilePath); logFile.MoveTo(prevLogFilePath); Action rollEventHandler = RolledLogFile; if (rollEventHandler != null) { rollEventHandler(); } } } } catch { // best effort for this method } }
public override void MoveTo(string destFileName) { FileInfoBase movedFileInfo = CopyTo(destFileName); Delete(); _path = movedFileInfo.FullName; }
private static string GetNamespaceFromCsproj(FileInfoBase fileToSearch) { string nameSpace; using (Stream fr = fileToSearch.OpenRead()) { StreamReader sr = new StreamReader(fr); string fileContents = sr.ReadToEnd(); // Look for a <RootNamespace> tag string openingTag = "<RootNamespace>"; string closingTag = "</RootNamespace>"; int openingIndex = fileContents.IndexOf(openingTag, StringComparison.OrdinalIgnoreCase); if (openingIndex > -1) { int closingIndex = fileContents.IndexOf(closingTag, openingIndex + openingTag.Length, StringComparison.OrdinalIgnoreCase); int substringStartingIndex = openingIndex + openingTag.Length; nameSpace = fileContents.Substring(substringStartingIndex, closingIndex - substringStartingIndex); } else { nameSpace = FileSystem.Path.GetFileNameWithoutExtension(fileToSearch.Name); } } return(nameSpace); }
public IProfile Create(string profileName) { if (Exists(profileName)) { throw new Core.Services.ProfileNameConflictException(profileName); } string profilePath = ProfilePath(profileName); FileInfoBase profileFileInfo = _fileSystem.FileInfo.FromFileName(profilePath); StreamWriter writer = profileFileInfo.CreateText(); using (CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(writer, leaveOpen: false)) { csvWriter.Configuration.QuoteAllFields = true; csvWriter.Configuration.RegisterClassMap(new CSV.MatchRecordConfiguration()); csvWriter.WriteHeader <MatchRecord>(); csvWriter.NextRecord(); } FileSystemProfile profile = new FileSystemProfile(_fileSystem, profileName, profilePath); AddToCache(profileName, profile); return(profile); }
private bool DetermineWhetherFileIsTheRootFile(Uri file, FileInfoBase rootfile) { var fileInfo = this.fileSystem.FileInfo.FromFileName(file.LocalPath); if (rootfile.DirectoryName != fileInfo.DirectoryName) { return(false); // they're not even in the same directory } if (rootfile.FullName == file.LocalPath) { return(true); // it's really the same file } if (fileInfo.Name == string.Empty) { return(true); // the file is actually the directory, so we consider that the root file } if (fileInfo.Name.StartsWith("index", StringComparison.InvariantCultureIgnoreCase)) { return(true); // the file is an index file, so we consider that the root } return(false); }
public static string GetDefaultNamespace(DirectoryInfoBase directory) { FileInfoBase[] fileInfos = FindAllCsprojFiles(directory); FileInfoBase fileToSearch = ChooseCsproj(fileInfos); return(GetNamespaceFromCsproj(fileToSearch)); }
/// <summary> /// Provides a common way for opening a file stream for exclusively deleting the file. /// </summary> private static Stream GetFileDeleteStream(FileInfoBase file) { Contract.Assert(file != null); // Open file exclusively for delete sharing only return(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); }
private async Task <ChauffeurDeliveryTable> Deliver(FileInfoBase file, IDictionary <string, string> @params) { var instructions = fileSystem.File .ReadAllLines(file.FullName) .Where(x => !string.IsNullOrEmpty(x)) .Where(x => !x.StartsWith("##")); var tracking = new ChauffeurDeliveryTable { Name = file.Name, ExecutionDate = DateTime.Now, Hash = HashDelivery(file), SignedFor = true }; if (!await AreAllParametersSpecified(instructions, @params)) { tracking.SignedFor = false; return(tracking); } foreach (var instruction in instructions) { var result = await host.Run(new[] { replaceTokens(@params, instruction) }); if (result != DeliverableResponse.Continue) { tracking.SignedFor = false; break; } } return(tracking); }
public File(string path, FileInfoBase info, LocalFileSource source) { this.Path = path; this.Name = Paths.GetFileNameWithoutExtension(path); this.Type = info; this.Source = source; }
public static void Extract(this ZipArchive archive, string directoryName) { foreach (ZipArchiveEntry entry in archive.Entries) { string path = Path.Combine(directoryName, entry.FullName); if (entry.Length == 0 && (path.EndsWith("/", StringComparison.Ordinal) || path.EndsWith("\\", StringComparison.Ordinal))) { // Extract directory FileSystemHelpers.CreateDirectory(path); } else { FileInfoBase fileInfo = FileSystemHelpers.FileInfoFromFileName(path); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } using (Stream zipStream = entry.Open(), fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write)) { zipStream.CopyTo(fileStream); } fileInfo.LastWriteTimeUtc = entry.LastWriteTime.ToUniversalTime().DateTime; } } }
protected override void OnLockAcquired() { OperationManager.SafeExecute(() => { // Create Sentinel file for DWAS to check // DWAS will check for presence of this file incase a an app setting based recycle needs to be performed in middle of deployment // If this is present, DWAS will postpone the recycle so that deployment goes through first if (!String.IsNullOrEmpty(siteRoot)) { FileSystemHelpers.CreateDirectory(Path.Combine(siteRoot, @"ShutdownSentinel")); string sentinelPath = Path.Combine(siteRoot, @"ShutdownSentinel\Sentinel.txt"); if (!FileSystemHelpers.FileExists(sentinelPath)) { var file = FileSystemHelpers.CreateFile(sentinelPath); file.Close(); } // DWAS checks if write time of this file is in the future then only postpones the recycle FileInfoBase sentinelFileInfo = FileSystemHelpers.FileInfoFromFileName(sentinelPath); sentinelFileInfo.LastWriteTimeUtc = DateTime.UtcNow.AddMinutes(20); } }); IRepositoryFactory repositoryFactory = RepositoryFactory; if (repositoryFactory != null) { IRepository repository = repositoryFactory.GetRepository(); if (repository != null) { // Clear any left over repository-related lock since we have the actual lock repository.ClearLock(); } } }
public static bool IsFullTextCompareFile(this FileInfoBase file, KuduSyncOptions kuduSyncOptions) { var matched = kuduSyncOptions.GetFullTextCompareFilePatterns() .Any(fileMatchPattern => Regex.IsMatch(file.Name, WildCardToRegular(fileMatchPattern), RegexOptions.IgnoreCase)); return(matched); }
/// <summary> /// Updates the file. /// </summary> /// <param name="zipArchive">The zip archive.</param> /// <param name="zipArchiveEntry">The zip archive entry.</param> /// <param name="fullName">The full name.</param> /// <param name="newFilePath">The new file path.</param> public void UpdateFile( ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry, string fullName, string newFilePath) { TraceService.WriteLine("ZipperService::UpdateFile fullName=" + fullName); FileInfoBase fileInfoBase = this.fileSystem.FileInfo.FromFileName(fullName); FileInfoBase newFileInfoBase = this.fileSystem.FileInfo.FromFileName(newFilePath); if (newFileInfoBase.LastWriteTime > fileInfoBase.LastWriteTime) { //// delete the current one! zipArchiveEntry.Delete(); //// and now add the new one! zipArchive.CreateEntryFromFile(newFilePath, fullName); TraceService.WriteLine(zipArchiveEntry.Name + " has been replaced"); } else { TraceService.WriteLine(zipArchiveEntry.Name + " has not been replaced"); } }
private XDocument ReadResultsFile(FileInfoBase testResultsFile) { XDocument document; using (var stream = testResultsFile.OpenRead()) { using (var streamReader = new System.IO.StreamReader(stream)) { string content = streamReader.ReadToEnd(); int begin = content.IndexOf("<!-- Pickles Begin", StringComparison.Ordinal); content = content.Substring(begin); content = content.Replace("<!-- Pickles Begin", string.Empty); int end = content.IndexOf("Pickles End -->", System.StringComparison.Ordinal); content = content.Substring(0, end); content = content.Replace("<", "<").Replace(">", ">"); var xmlReader = XmlReader.Create(new System.IO.StringReader(content)); document = XDocument.Load(xmlReader); } } return(document); }
static void ListDirectory(DirectoryInfoBase dir) { FileSystemInfoBase[] children = dir.GetFileSystemInfos(); Console.WriteLine(); Console.WriteLine(" Directory of {0}", dir.FullName.TrimEnd('\\')); Console.WriteLine(); foreach (DirectoryInfoBase info in children.Where(d => d is DirectoryInfoBase)) { Console.WriteLine(String.Format("{0} <DIR> {1}", ToDisplayString(info.LastWriteTime), info.Name)); } int count = 0; long total = 0; foreach (FileInfoBase info in children.Where(d => !(d is DirectoryInfoBase))) { FileInfoBase file = (FileInfoBase)info; Console.WriteLine(String.Format("{0} {1,17} {2}", ToDisplayString(info.LastWriteTime), file.Length.ToString("#,##0"), info.Name)); total += file.Length; ++count; } Console.WriteLine(String.Format("{0,16} File(s) {1,14} bytes", count.ToString("#,##0"), total.ToString("#,##0"))); }
/// <summary> /// Provides a common way for opening a file stream for exclusively deleting the file. /// </summary> private static Stream GetFileDeleteStream(FileInfoBase file) { ArgumentNullException.ThrowIfNull(file); // Open file exclusively for delete sharing only return(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); }
private void SmartDeleteFile(FileInfoBase fileToDelete) { TryFileFuncAndMoveFileOnFailure(() => { fileToDelete.Delete(); return(null); }, fileToDelete.FullName); }
public override bool Test(FileInfoBase file) { if (IsStackEmpty()) { throw new InvalidOperationException("Can't test file before enters any directory."); } if (Frame.IsNotApplicable) { return false; } return IsLastSegment() && TestMatchingSegment(file.Name); }
public void MockFileData_AcceptsFuncAndReturnsContents() { // create a file in a source file system var sourceFileSystem = new MockFileSystem(); sourceFileSystem.File.WriteAllBytes(sourceFileName, fileContent); sourceFileSystem.File.SetAttributes(sourceFileName, attributes); sourceFileSystem.File.SetCreationTime(sourceFileName, dateCreated); sourceFileSystem.File.SetLastWriteTime(sourceFileName, dateLastWritten); sourceFileSystem.File.SetLastAccessTime(sourceFileName, dateLastAccessed); var sourceFile = sourceFileSystem.DirectoryInfo.FromDirectoryName(Path.GetDirectoryName(sourceFileName)).GetFiles().Single(); // create a new destination file system and copy the source file there var dfs = new MockFileSystem(); dfs.AddFile(destinationFileName, new MockFileData(sourceFileSystem, sourceFile)); destinationFileInfo = dfs.DirectoryInfo.FromDirectoryName(Path.GetDirectoryName(destinationFileName)).GetFiles().Single(); destinationFileSystem = dfs; }
private bool FillAllBin(IList<BinInformation> binInfoList, ref int rowIndex, FileInfoBase dtFileInfo) { foreach (BinInformation binInfo in binInfoList) { if (binInfo.IsValid) { this.FillOneBinValue(dtFileInfo, rowIndex, binInfo); rowIndex++; } } return true; }
private bool FillOneBinValue(FileInfoBase dtFileInfo, int rowIndex, BinInformation binInfo) { float[] tempModelValue = new float[base.modelCoeNum]; this.CalculateModelValue(dtFileInfo.CellInfo, binInfo, ref tempModelValue); int num = 0; for (int i = 0; i < base.modelCoeNum; i++) { base.allCoeValueMatrix[(rowIndex * base.modelCoeNum) + num] = tempModelValue[i]; num++; } base.actualLossMatrix[rowIndex] = binInfo.ActualPathLoss; return true; }
private bool FillAllProportionBin(FileInfoBase dtFileInfo, int rowIndex) { foreach (BinInformation binInfo in dtFileInfo.BinInfoList) { if (binInfo.IsValid) { this.FillOneProportionBinValue(dtFileInfo, rowIndex, binInfo); rowIndex++; } } return true; }
private void FillOneProportionBinValue(FileInfoBase dtFileInfo, int rowIndex, BinInformation binInfo) { if (binInfo.ClutterProportion != null) { for (int i = 0; i < base.m_ClutterTypeNum; i++) { base.proportionMatrix[(rowIndex * base.m_ClutterTypeNum) + i] = binInfo.ClutterProportion[i]; } } }