From 3141e1f02036c9d2350bd2c581ef0af78ecc7d4e Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Mon, 2 Dec 2024 11:43:04 -0500 Subject: [PATCH] Add file size helper extension --- BinaryObjectScanner.Test/ExtensionsTests.cs | 20 ++++++++++++++++++++ BinaryObjectScanner/Extensions.cs | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/BinaryObjectScanner.Test/ExtensionsTests.cs b/BinaryObjectScanner.Test/ExtensionsTests.cs index ceb5284c..af7136c4 100644 --- a/BinaryObjectScanner.Test/ExtensionsTests.cs +++ b/BinaryObjectScanner.Test/ExtensionsTests.cs @@ -6,6 +6,26 @@ namespace BinaryObjectScanner.Test { public class ExtensionsTests { + #region FileSize + + [Fact] + public void FileSize_Null_Invalid() + { + string? filename = null; + long actual = filename.FileSize(); + Assert.Equal(-1, actual); + } + + [Fact] + public void FileSize_Empty_Invalid() + { + string? filename = string.Empty; + long actual = filename.FileSize(); + Assert.Equal(-1, actual); + } + + #endregion + #region IterateWithAction [Fact] diff --git a/BinaryObjectScanner/Extensions.cs b/BinaryObjectScanner/Extensions.cs index db2ad0cf..02f8dff7 100644 --- a/BinaryObjectScanner/Extensions.cs +++ b/BinaryObjectScanner/Extensions.cs @@ -1,10 +1,28 @@ using System; using System.Collections.Generic; +using System.IO; namespace BinaryObjectScanner { internal static class Extensions { + /// + /// Helper to get the filesize from a path + /// + /// Size of the file path, -1 on error + public static long FileSize(this string? filename) + { + // Invalid filenames are ignored + if (string.IsNullOrEmpty(filename)) + return -1; + + // Non-file paths are ignored + if (!File.Exists(filename)) + return -1; + + return new FileInfo(filename).Length; + } + /// /// Wrap iterating through an enumerable with an action ///