Skip to content

RotatingStreamWriter.GenerateUniqueFileName: null-forgiving operator on Path.GetDirectoryName #101

@Christophe-Rogiers

Description

@Christophe-Rogiers

Bug Description

In GenerateUniqueFileName(), Path.GetDirectoryName() can return null (e.g. for root paths like C:\ or relative filenames without a directory component). The null-forgiving operator ! suppresses the compiler warning but does not prevent a NullReferenceException at runtime if directory is subsequently used in path operations.

Actual Behavior

// RotatingStreamWriter.cs lines 241-242
string directory = Path.GetDirectoryName(basePath)!;
string fileName = Path.GetFileName(basePath);

If basePath is a root path or a bare filename (e.g. "output.log" without directory), GetDirectoryName returns null or "", and downstream Path.Combine(directory, ...) will produce unexpected results or throw.

Suggested Fix

Handle the null case explicitly with a fallback to the current directory:

string directory = Path.GetDirectoryName(basePath) ?? string.Empty;
string fileName = Path.GetFileName(basePath);

Or validate early and throw a descriptive error:

string? directory = Path.GetDirectoryName(basePath);
if (string.IsNullOrEmpty(directory))
    throw new ArgumentException($"Cannot determine directory from path: {basePath}", nameof(basePath));

Environment

  • File: src/Servy.Core/IO/RotatingStreamWriter.cs
  • Line: 241

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions