Пример #1
0
        public static bool FilesContentsAreEqual(IFileInfo fileInfo1, IFileInfo fileInfo2)
        {
            bool result;

            if (fileInfo1.Exists != fileInfo2.Exists)
            {
                return(false);
            }

            if (fileInfo1.Length != fileInfo2.Length)
            {
                result = false;
            }
            else
            {
                using (var file1 = fileInfo1.OpenRead())
                {
                    using (var file2 = fileInfo2.OpenRead())
                    {
                        result = StreamsContentsAreEqual(file1, file2);
                    }
                }
            }

            return(result);
        }
Пример #2
0
        private async Task Compress(ZipArchiveEntry entry, IFileInfo sourceFile, CancellationToken cancellationToken)
        {
            Logger.Verbose("Compressing file: {File}", sourceFile.FullName);

            using var source      = sourceFile.OpenRead();
            using var destination = entry.Open();
            await source.CopyToAsync(destination, cancellationToken);
        }
Пример #3
0
        /// <summary>
        /// Use only if you don't reuse the stream/stream reader anymore.
        /// </summary>
        async Task <BlogEntry> IFormatter.GetBlogEntryAsync(IFileInfo info)
        {
            using StreamReader reader = new(info.OpenRead());
            var entry = await(this as IFormatter).GetBlogHeadAsync(info, reader).ConfigureAwait(false);

            entry.Summary = await GetSummaryAsync(reader).ConfigureAwait(false);

            return(entry);
        }
        protected internal override bool IsValidFileResourceInternal(IFileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            return(this.IsValidResource(file.OpenRead()));
        }
Пример #5
0
        public static async Task <byte[]> ReadAllBytes(IFileInfo fileInfo)
        {
            using (var stream = fileInfo.OpenRead())
            {
                var result = new byte[stream.Length];
                await stream.ReadAsync(result, 0, (int)stream.Length);

                return(result);
            }
        }
Пример #6
0
        /// <summary>
        /// Creates a new <see cref="FileInstance"/> for the specified file.
        /// </summary>
        private FileInstance createFileInstance(IDirectoryInfo baseDirectory, IFileInfo file)
        {
            string relativePath = file.GetRelativePath(baseDirectory);

            using (System.IO.Stream stream = file.OpenRead())
            {
                long    fileSize         = stream.Length;
                Hash256 fileContentsHash = Hash256.GetContentsHash(stream);
                return(new FileInstance(relativePath, fileSize, fileContentsHash));
            }
        }
Пример #7
0
        public void ReadFile_With_OpenRead()
        {
            IFileInfo fileInfo = _factory.CreateFileInfo(_EXAMPLE_FILE_PATH);

            using (IFileStream stream = fileInfo.OpenRead())
                using (IStreamReader reader = _factory.CreateReader(stream))
                {
                    string content = reader.ReadToEnd();
                    Console.WriteLine("[ViaFileInfo.ReadFile_With_OpenRead] File content: " + content);
                }
        }
Пример #8
0
 public static string GetFileHash(IFileInfo file)
 {
     using (var stream = file.OpenRead())
     {
         using (var hasher = new MD5CryptoServiceProvider())
         {
             var hashBytes = hasher.ComputeHash(stream);
             return(BitConverter.ToString(hashBytes).Replace("-", string.Empty));
         }
     }
 }
Пример #9
0
 /// <summary>
 ///     Gets the <see cref="IFileInfo" /> hash.
 /// </summary>
 /// <param name="fileInfo">The file information.</param>
 /// <returns>
 ///     <see cref="string" /> hash
 /// </returns>
 public string GetFileHash(IFileInfo fileInfo)
 {
     if (fileInfo.Exists)
     {
         using (var md5 = MD5.Create())
         {
             using (var stream = fileInfo.OpenRead())
             {
                 return(Convert.ToBase64String(md5.ComputeHash(stream)));
             }
         }
     }
     return(null);
 }
Пример #10
0
 public List <FileRecord> Load(IFileInfo file)
 {
     using (var stream = file.OpenRead())
         using (var reader = new StreamReader(stream))
             using (var csvReader = new CsvReader(reader))
             {
                 csvReader.Configuration.RegisterClassMap <FileRecordMap>();
                 csvReader.Configuration.ReadingExceptionOccurred = (ex) =>
                 {
                     logger.LogError(ex, $"Row record:{csvReader.Context.RawRecord}");
                     return(false);
                 };
                 return(csvReader.GetRecords <FileRecord>().ToList());
             }
 }
Пример #11
0
        private ADT ReadADT(int x, int y)
        {
            string    file     = GetAdtFileName(x, y);
            IFileInfo fileInfo = FileInfoFactory.Create();

            if (fileInfo.Exists(file) == false)
            {
                throw new Exception(String.Format("ADT Doesn't exist: {0}", file));
            }

            using (var reader = new BinaryReader(fileInfo.OpenRead(file)))
            {
                return(new ADTChunkFileParser(reader).Parse());
            }
        }
Пример #12
0
        public string GenerateFrom(IFileInfo fileInfo)
        {
            if (fileInfo.Length < 1)
            {
                return(EmptyFileHash);
            }

            using var sha256 = SHA256.Create();

            using var bf = new BufferedStream(fileInfo.OpenRead(), 1024 * 1024 * 10);

            var hash = BitConverter.ToString(sha256.ComputeHash(bf)).Replace("-", string.Empty).ToLowerInvariant();

            return(hash);
        }
Пример #13
0
        private static void PipeFileContents(IFileInfo file, Stream pOut, int bufSize)
        {
            FileStreamBase inputStream = file.OpenRead();

            byte[] buf = new byte[bufSize];

            int len;

            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                pOut.Write(buf, 0, len);
            }

            pOut.Dispose();
            inputStream.Dispose();
        }
Пример #14
0
        public static IEnumerable <string> GetLines(this IFileInfo fileInfo)
        {
            using (var stream = fileInfo.OpenRead())
            {
                using (var streamReader = new StreamReader(stream))
                {
                    var nextLine = streamReader.ReadLine();

                    while (nextLine != null)
                    {
                        yield return(nextLine);

                        nextLine = streamReader.ReadLine();
                    }
                }
            }
        }
Пример #15
0
        public static string Hash(this IFileInfo fileInfo, IHashAlgorithm hashAlgorithm = null)
        {
            if (hashAlgorithm == null)
            {
                hashAlgorithm = Hashing.Default;
            }

            using (hashAlgorithm)
            {
                using (var stream = fileInfo.OpenRead())
                {
                    var hash = hashAlgorithm.ComputeHex(stream);

                    return(hash);
                }
            }
        }
Пример #16
0
 /// <summary>
 ///     Reads the bytes of a file.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <returns>
 ///     <see cref="byte" /> array
 /// </returns>
 /// <exception cref="System.IO.FileNotFoundException"></exception>
 public byte[] ReadBytes(IFileInfo file)
 {
     if (!file.Exists)
     {
         throw new FileNotFoundException(file.FullName);
     }
     byte[] bytes;
     using (var stream = file.OpenRead())
     {
         using (var memoryStream = new MemoryStream())
         {
             var task = stream.CopyToAsync(memoryStream);
             task.Wait();
             bytes = memoryStream.ToArray();
         }
     }
     return(bytes);
 }
Пример #17
0
        private void When_opening_file_for_reading_it_must_succeed()
        {
            // Arrange
            const string path = @"C:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                                     .IncludingTextFile(path, DefaultContents)
                                     .Build();

            IFileInfo info = fileSystem.ConstructFileInfo(path);

            // Act
            using (IFileStream stream = info.OpenRead())
            {
                // Assert
                stream.CanRead.Should().BeTrue();
                stream.CanWrite.Should().BeFalse();
            }
        }
Пример #18
0
        private InternalDockerSource CreateFromImageConfigFile(IFileInfo file)
        {
            try
            {
                using var readStream = file.OpenRead();
                using var reader     = new StreamReader(readStream);
                var fileContents = reader.ReadToEnd();

                var imageConfig = JsonHelper.Deserialise <ImageConfig>(fileContents);

                return(new InternalDockerSource(file.Directory, imageConfig));
            }
            catch (Exception exception)
            {
                _logger.LogError($"Unable to read internal Docker source from image config at '{file?.FullName}': {exception.Message}");

                return(null);
            }
        }
Пример #19
0
        public async Task FileIsNotChangedAfterReSaving()
        {
            await setupLocalisation(
                new LocalisationMember("prop", "property", "property"),
                new LocalisationMember("method", "method", "method",
                                       new LocalisationParameter("int", "i")));

            IFileInfo file    = mockFs.FileInfo.FromFileName(test_file_name);
            string    initial = await mockFs.File.ReadAllTextAsync(file.FullName, CancellationToken.None);

            // Read and re-save via LocalisationFile.
            LocalisationFile localisation;

            using (var stream = file.OpenRead())
                localisation = await LocalisationFile.ReadAsync(stream);
            using (var stream = file.OpenWrite())
                await localisation.WriteAsync(stream, workspace);

            string updated = await mockFs.File.ReadAllTextAsync(file.FullName, CancellationToken.None);

            Assert.Equal(initial, updated);
        }
Пример #20
0
		private static void PipeFileContents(IFileInfo file, Stream pOut, int bufSize)
		{
			FileStreamBase inputStream = file.OpenRead();
			byte[] buf = new byte[bufSize];

			int len;
            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                pOut.Write(buf, 0, len);
            }

			pOut.Dispose();
			inputStream.Dispose();
		}