DEV Community

Cover image for C# file/folder helpers
Karen Payne
Karen Payne

Posted on • Updated on

C# file/folder helpers

There are times when the working with files and folders a developer runs into unusual task that for some may be difficult to figure out or takes too much time to code.

Bookmark this article for methods for working with files and folders and overtime more code samples will be added as there are many more to come. What will not be added are methods easy to find on the Internet.

Requires

  • Microsoft Visual Studio 2022 or higher
  • .NET Core 7 or higher

Is folder or file

When traversing a folder a developer may want to know if an item is a file or folder.

The following method will, if successful indicate if an item is a file or folder and if the item does not exists the method returns false.

public static (bool isFolder, bool success) IsFileOrFolder(string path)
{
    try
    {
        var attr = File.GetAttributes(path);
        return attr.HasFlag(FileAttributes.Directory) ? (true, true)! : (false, true)!;
    }
    catch (FileNotFoundException)
    {
        return (false, false);
    }
}
Enter fullscreen mode Exit fullscreen mode

In the following example, LogFile folder exists, its created using a msbuild task, Log does not exists but TextFile1.txt does exists.

static void Main(string[] args)
{
    var items = new List<string>
    {
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogFiles"),
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"),
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt")
    };

    foreach (var item in items)
    {
        var (isFolder, success) = FileHelpers.IsFileOrFolder(item);
        if (success)
        {
            AnsiConsole.MarkupLine($"{item}");
            AnsiConsole.MarkupLine($"\tIs folder {isFolder}");
        }
        else
        {
            AnsiConsole.MarkupLine($"[white]{item}[/] [red]not found[/]");
        }
    }

    Console.ReadLine();
}
Enter fullscreen mode Exit fullscreen mode

Is file locked

The following method detects if a file is locked when a file is opened with the attribute FileShare.None. Typical example, a developer does not close an Excel file properly or has the Excel file open outside the project.

This will not work if a file is open in shared mode.

public static async Task<bool> CanReadFile(string fileName)
{
    static bool IsFileLocked(Exception exception)
    {
        var errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
        return errorCode is ErrorSharingViolation or ErrorLockViolation;
    }

    try
    {
        await using var fileStream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        if (fileStream != null)
        {
            fileStream.Close();
        }
    }
    catch (IOException ex)
    {
        if (IsFileLocked(ex))
        {
            return false;
        }
    }

    await Task.Delay(50);

    return true;

}
Enter fullscreen mode Exit fullscreen mode

See the project IsFileLockedSample for an interactive example with an Excel file and a text file.

Natural sort file names

The following methods will sort file names that end in numbers or an array or list with strings ending in numbers the same as in Windows Explorer.

public class NaturalStringComparer : Comparer<string>
{

    [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
    private static extern int StrCmpLogicalW(string x, string y);

    public override int Compare(string x, string y)
        => StrCmpLogicalW(x, y);
}
Enter fullscreen mode Exit fullscreen mode

Example with a list of unsorted strings.

using System.Runtime.CompilerServices;
using Spectre.Console;
using static HelperLibrary.FileHelpers;

namespace NaturalSortSample;

internal class Program
{
    static void Main(string[] args)
    {
        StandardSortSample();
        NaturalSortSample();
        Console.ReadLine();
    }

    private static void NaturalSortSample()
    {
        Print("Natural sort");
        var fileNames = FileNames();

        fileNames.Sort(new NaturalStringComparer());

        foreach (var item in fileNames)
        {
            Console.WriteLine(item);
        }

    }
    private static void StandardSortSample()
    {
        Print("Standard sort");
        var fileNames = FileNames();

        foreach (var item in fileNames)
        {
            Console.WriteLine(item);
        }


    }

    private static List<string> FileNames() =>
        new()
        {
            "Example12.txt", "Example2.txt", "Example3.txt", "Example4.txt",
            "Example5.txt", "Example6.txt", "Example7.txt", "Example8.txt",
            "Example9.txt", "Example10.txt", "Example11.txt", "Example1.txt",
            "Example13.txt", "Example14.txt", "Example15.txt", "Example16.txt",
            "Example17.txt", "Example18.txt", "Example19.txt", "Example20.txt"
        };

    private static void Print(string text)
    {
        AnsiConsole.MarkupLine($"[yellow]{text}[/]");
    }

    [ModuleInitializer]
    public static void Init()
    {
        Console.Title = "Code sample";
        W.SetConsoleWindowPosition(W.AnchorWindow.Center);
    }
}
Enter fullscreen mode Exit fullscreen mode

Globbing

File globbing can in specific cases allow a developer to fine tune files that are looking for in a folder or folders.

Provides

  • Inclusion of files via patterns
  • Exclusion of file via patterns

Base patterns

Value Description
*.txt All files with .txt file extension.
*.* All files with an extension
* All files in top-level directory.
.* File names beginning with '.'.
*word* All files with 'word' in the filename.
readme.* All files named 'readme' with any file extension.
styles/*.css All files with extension '.css' in the directory 'styles/'.
scripts/*/* All files in 'scripts/' or one level of subdirectory under 'scripts/'.
images*/* All files in a folder with name that is or begins with 'images'.
**/* All files in any subdirectory.
dir/**/* All files in any subdirectory under 'dir/'.
../shared/* All files in a diretory named "shared" at the sibling level to the base directory

In this project (Razor Pages) the goal is to get all .cs file with several exclusions as per the variable exclude

await GlobbingOperations.Find(path, include, exclude); traverses the path which in this case is the current solution folder and on a match adds the match to a StringBuilder which we return the page and append to the body of the page the results.

public class IndexModel : PageModel
{
    public IndexModel()
    {
        GlobbingOperations.TraverseFileMatch += TraverseFileMatch;
    }

    [BindProperty]
    public StringBuilder Builder { get; set; } = new();
    public void OnGet()
    {

    }

    public async Task<PageResult> OnPost()
    {
        string path = DirectoryHelper.SolutionFolder();

        string[] include = { "**/*.cs", "**/*.cshtml" };
        string[] exclude =
        {
            "**/*Assembly*.cs",
            "**/*_*.cshtml",
            "**/*Designer*.cs",
            "**/*.g.i.cs",
            "**/*.g.cs",
            "**/TemporaryGeneratedFile*.cs"
        };

        Builder = new StringBuilder();
        await GlobbingOperations.Find(path, include, exclude);
        return Page();
    }

    private void TraverseFileMatch(FileMatchItem sender)
    {
        Log.Information(Path.Combine(sender.Folder, sender.FileName));
        Builder.AppendLine(Path.Combine(sender.Folder, sender.FileName));
    }
}
Enter fullscreen mode Exit fullscreen mode

How to create auto-incrementing file names

A developer may need to create file names that increment e.g. file1.txt, file2.txt etc.

The code presented shows how to in DirectoryHelpersLibrary.GenerateFiles For use in your application

  • Copy GenerateFiles.cs to your project
  • Change property _baseFileName to the base file name for creating, currently is set to data.
  • Change property _baseExtension to the file extension you want.

In the code sample each time the program runs it creates three .json files.

First time, Data_1.json, Data_2.json and Data_3.json
Second time, Data_4.json, Data_5.json and Data_6.json

And so on.

Provided code sample

static void Main(string[] args)
{
    AnsiConsole.MarkupLine(GenerateFiles.HasAnyFiles()
        ? $"Last file [cyan]{Path.GetFileName(GenerateFiles.GetLast())}[/]"
        : "[cyan]No files yet[/]");

    JsonSerializerOptions options = JsonSerializerOptions();
    AnsiConsole.MarkupLine("[white on blue]Create files[/]");
    foreach (var person in MockedData.PeopleMocked())
    {
        var (success, fileName) = GenerateFiles.CreateFile();
        if (success)
        {
            AnsiConsole.MarkupLine($"   [white]{Path.GetFileName(fileName)}[/]");
            File.WriteAllText(fileName, JsonSerializer.Serialize(person, options));
        }
        else
        {
            AnsiConsole.MarkupLine($"[red]Failed to create {fileName}[/]");
        }


    }

    Console.WriteLine();
    AnsiConsole.MarkupLine($"[white]Next file to be created[/] {Path.GetFileName(GenerateFiles.NextFileName())}");

    AnsiConsole.MarkupLine("[cyan]Done[/]");
    Console.ReadLine();
}
Enter fullscreen mode Exit fullscreen mode
Method Description
CreateFile Generate next file in sequence
RemoveAllFiles Removes files generated
HasAnyFiles Provides a count of generated files
NextFileName Get next file name without creating the file
GetLast Get last generated file name

Stay tune for more

More useful methods will be added over time.

Source code

Clone the following GitHub repository.

Top comments (2)

Collapse
 
ant_f_dev profile image
Anthony Fung

Hi Karen.

Having a list of these helper functions is a great idea!

If I may, I'd like to make a suggestions for Is folder or file. Instead of catching a FileNotFoundException, would it be possible to use one of

to check whether the file/directory exists?

Checking whether the file/directory exists would allow invalid paths to be handled without needing to throw an exception.

Collapse
 
karenpayneoregon profile image
Karen Payne

That is an option, my expectations are developers will find alternatives to what I have presented and make their own. Thanks.