Add a DirectoryPath property to DirectoryNotFoundException to be consistent with FileNotFoundException
Background and motivation
The DirectoryNotFoundException type does not provide any way for the thrower to specify the actual directory path in a machine-readable way such that any downstream/consuming program code that catches the exception can isolate the directory-path; currently we're forced to try to parse the human-readable .Message property which, additionally, might be a localized string and thus impossible to reliably process under all circumstances, which is important in error-handling functions.
It's also inconsistent with how FileNotFoundException has a String FileName { get; } property.
I did search through all 7 pages of existing Issues in the runtime repo matching "DirectoryNotFoundException" - none of them are a request to add a directory-path property to the exception.
API Proposal
namespace System.IO;
public class DirectoryNotFoundException : IOException
{
public DirectoryNotFoundException (string? message, string? directoryPath, Exception? innerException)
: this(message: message, innerException: innerException)
{
this.DirectoryPath = directoryPath;
}
public DirectoryNotFoundException (string? message, string? directoryPath)
: this(message: message)
{
this.DirectoryPath = directoryPath;
}
public string? DirectoryPath { get; }
}
API Usage
public static void ExampleMethodThatCopiesFilesAround(DirectoryInfo source, DirectoryInfo dest)
{
if (!source.Exists) throw new DirectoryNotFoundException(message: "Source directory does not exist.", directoryPath: source.FullName);
if (!dest.Exists) throw new DirectoryNotFoundException(message: "Destination directory does not exist.", directoryPath: dest.FullName);
foreach (FileInfo fi in source.GetFiles())
{
// etc...
}
}
//
using Microsoft.Extensions.Logging;
public void ConsumingMethodWithLogger()
{
try
{
ExampleMethodThatCopiesFilesAround(source: foo, dest: bar);
}
catch (DirectoryNotFoundException dEx)
{
using (this.logger.BeginScope("DirectoryPath", dEx.DirectoryPath))
{
this.logger.LogError(exception: dEx, message: "Directory not found: {DirectoryPath}", dEx.DirectoryPath);
}
}
}
Alternative Designs
No response
Risks
This change involves only adding additional (and entirely optional and nullable) constructor overloads and properties.
It's possible that there exists user-code that subclasses DirectoryNotFoundException to add their own property for the missing directory's full-path, but I assume this wouldn't be an ABI breaking change because user subclasses would still be using a different class member "slot" (right?)
Tagging subscribers to this area: @dotnet/area-system-io See info in area-owners.md if you want to be subscribed.
There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.
There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.
Right - this DirectoryPath value is entirely optional, for the benefit of users when such a path is available, such as in my example.
It's the same with FileNotFoundException: code that instantiates FileNotFoundException is not required to provide the file-name, but if it's available and the throwing code wants to then it provides a machine-readable way for catch code to get the path, for example, for logging or better error-messages in the UI.
There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.
@huoyaoyuan the same situation occurs with HttpRequestException where a status code is not always present. In that case, the StatusCode property was made nullable.
Same would apply here.
- We discussed making the property non-null but decided it was simpler to just store what we were given
- Also consistent with
FileNotFoundException
- Also consistent with
- If
messageisnullbut adirectoryPathis givenMessageshould return a constructed one, similar toFileNotFoundException
namespace System.IO;
public partial class DirectoryNotFoundException
{
// Existing ctors
// public DirectoryNotFoundException();
// public DirectoryNotFoundException(String);
// public DirectoryNotFoundException(SerializationInfo, StreamingContext);
// public DirectoryNotFoundException(String, Exception);
public DirectoryNotFoundException(string? message, string? directoryPath);
public DirectoryNotFoundException(string? message, string? directoryPath, Exception? innerException);
public string? DirectoryPath { get; }
}
If
messageis null but a directoryPath is given Message should return a constructed one, similar toFileNotFoundException
I did consider that when I wrote-up my initial proposal, but I was wary of the risk of unintentional information disclosure (I understand this is the same reason why KeyNotFoundException doesn't expose the key-that-wasn't-found). But if you're fine with that then I'm fine with that.
@terrajobst If message is null but a
directoryPathis givenMessageshould return a constructed one, similar toFileNotFoundException
I've started my implementation and hit a minor problem with the .Message generation part: I was modelling my impl off FileNotFoundException - but its .Message string factory ends-up being a call into the CLR via FileLoadException.FormatFileLoadExceptionMessage.
Should I just write my own equivalent message strings in SR then?
@jozkee should be able to guide you
Should I just write my own equivalent message strings in SR then?
Yes. Feel free to send a draft PR and we can further discuss the approach.
Is anybody working on this currently? It seems not and nobody has commented or made any PRs addressing this issue.
I can start working on it if that's okay with you, @jozkee
@Flu I completely overlooked @jozkee's reply - I'll find my changes and submit a draft PR soon then. My apologies.
Hi! Just checking in since it’s been over a year since the last update. @daiplusplus, are you still planning to submit a draft PR? If not, I would like to pick this up. Of course, happy to step aside if you’re still working on it. Thanks!
go ahead @ViveliDuCh (I was about to assign to copilot!)
(I'm using this as a sample issue for testing an AI workflow. I'm not intending to commit the fix -- unless there ends up being no progress on this for a while again)