Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions docs/standard/commandline/get-started-tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,11 +340,10 @@ scl quotes delete --search-terms David "You can do" Antoine "Perfection is achie

:::code language="csharp" source="snippets/get-started-tutorial/csharp/Stage3/Program.cs" id="fileoption" :::

This code uses <xref:System.CommandLine.Parsing.ArgumentResult> to provide custom parsing, validation, and error handling.
This code uses two separate mechanisms:

Without this code, missing files are reported with an exception and stack trace. With this code just the specified error message is displayed.

This code also specifies a default value, which is why it sets <xref:System.CommandLine.Option`1.DefaultValueFactory?displayProperty=nameWithType> to custom parsing method.
* <xref:System.CommandLine.Option`1.DefaultValueFactory?displayProperty=nameWithType> supplies `sampleQuotes.txt` as the default when you don't provide `--file`. When you do provide `--file`, the option's built-in parser converts the token to a `FileInfo` directly — `DefaultValueFactory` doesn't run.
* <xref:System.CommandLine.Option`1.Validators?displayProperty=nameWithType> adds a custom validator that runs *after* the value is parsed, whether you supplied a path or the default was used. Without the validator, a missing file would cause an unhandled `FileNotFoundException` with a stack trace. With the validator, just the specified error message is displayed.
Comment thread
gewarren marked this conversation as resolved.
Outdated

1. After the code that creates `lightModeOption`, add options and arguments for the `add` and `delete` commands:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,16 @@ static int Main(string[] args)
{
Description = "An option whose argument is parsed as a FileInfo",
Required = true,
DefaultValueFactory = result =>
DefaultValueFactory = _ => new FileInfo("sampleQuotes.txt")
};
fileOption.Validators.Add(result =>
{
var file = result.GetValueOrDefault<FileInfo>();
if (file is not null && !file.Exists)
{
if (result.Tokens.Count == 0)
{
return new FileInfo("sampleQuotes.txt");

}
string filePath = result.Tokens.Single().Value;
if (!File.Exists(filePath))
{
result.AddError("File does not exist");
return null;
}
else
{
return new FileInfo(filePath);
}
result.AddError("File does not exist");
}
};
});
// </fileoption>

Option<int> delayOption = new("--delay")
Expand Down
Loading