Skip to content
Open
Show file tree
Hide file tree
Changes from all 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`. `DefaultValueFactory` doesn't run when you do provide `--file`.
* <xref:System.CommandLine.Option`1.CustomParser?displayProperty=nameWithType> runs when you explicitly provide `--file`. It converts the token to a `FileInfo` and validates that the file exists. Without validation, a missing file would cause an unhandled `FileNotFoundException` with a stack trace. With validation, just the specified error message is displayed.

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 @@ -11,24 +11,15 @@ static int Main(string[] args)
Option<FileInfo> fileOption = new("--file")
{
Description = "An option whose argument is parsed as a FileInfo",
Required = true,
DefaultValueFactory = result =>
DefaultValueFactory = _ => new FileInfo("sampleQuotes.txt"),
CustomParser = result =>
{
if (result.Tokens.Count == 0)
{
return new FileInfo("sampleQuotes.txt");

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