• NeonSDK
  • NeonKUBE
Search Results for

    Show / Hide Table of Contents
    • Neon
      • Build
    • Neon.Blazor
      • BlazorHelper
      • BodyOutlet
      • ClientRenderContext
      • DOMRectReadOnly
      • EventHandlers
      • FileDownloader
      • HtmlElement
      • IRenderContext
      • IntersectionChangedEventArgs
      • IntersectionObserver
      • IntersectionObserverContext
      • MobileDetector
      • NeonBlazorExtensions
      • ServerRenderContext
      • SwipeDirection
      • SwipeHandler
    • Neon.Blazor.Analyzers
      • SvgGenerator
      • SvgGenerator.Svg
    • Neon.BuildInfo
      • ThisAssembly
      • ThisAssembly.Git
      • ThisAssembly.Git.BaseVersion
      • ThisAssembly.Git.SemVer
    • Neon.CSharp
      • CSharpHelper
      • CompilerErrorException
      • MetadataReferences
    • Neon.Cassandra
      • KeyspaceStatus
      • RowSetExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
      • SessionExtensions
    • Neon.Collections
      • ArgDictionary
      • Bits
      • IObjectDictionary
      • NiceDictionary<TKey, TValue>
      • ObjectDictionary
    • Neon.Common
      • AppDomainExtensions
      • Block
      • BlockArray
      • ByteEncoding
      • ByteUnits
      • CommandLine
      • CommandLine.OptionDefinition
      • CommandLine.Redactor
      • CpuArchitecture
      • Credentials
      • DateTimeExtensions
      • EnumExtensions
      • EnvironmentParser
      • EnvironmentParser.Parser<T>
      • EnvironmentParser.Validator<T>
      • EnvironmentParser.VariableSource
      • ExceptionExtensions
      • ExecuteException
      • ExecuteResponse
      • GlobPattern
      • HexDumpOption
      • HttpClientExtensions
      • HttpResponseMessageExtensions
      • IEnumerableExtensions
      • ILabeled
      • IOExtensions
      • IServiceContainer
      • IStaticDirectoryExtensions
      • LabelSelector
      • LabelSelectorOptions
      • LabelSelector<TItem>
      • NeonAssemblyExtensions
      • NeonExtendedHelper
      • NeonHelper
      • NetFramework
      • NewtonsoftExtensions
      • NotReadyException
      • ProcessExtensions
      • ProgramEntrypoint
      • ProgramEntrypointAsync
      • ProgramExitException
      • ProgramRunner
      • RandomExtensions
      • ReflectionExtensions
      • SemanticVersion
      • ServiceContainer
      • StaticZipOptions
      • StringBuilderExtensions
      • StringExtensions
      • Stub
      • Stub.Value
      • TaskExtensions
      • TimeSpanExtensions
      • ToolException
      • TriState
      • WeakEventController
      • WindowsEdition
      • WindowsFeatureStatus
      • YamlDotNetExtensions
    • Neon.Cryptography
      • AesCipher
      • CryptoExtensions
      • CryptoHelper
      • NeonVault
      • Wildcard
    • Neon.Csv
      • CsvReader
      • CsvTableReader
      • CsvTableWriter
      • CsvWriter
    • Neon.Data
      • DateTimeJsonConverter
      • DateTimeOffsetJsonConverter
      • IEnhancedJsonConverter
      • IGeneratedServiceClient
      • IPersistableType
      • IPersistableType<T>
      • IRoundtripData
      • IntegerEnumConverter<TEnum>
      • NotifyPropertyChanged
      • RoundtripDataFactory
      • RoundtripDataHelper
      • TimeSpanJsonConverter
      • VersionJsonConverter
    • Neon.Deployment
      • AwsCli
      • DeploymentException
      • DeploymentHelper
      • DownloadManifest
      • DownloadPart
      • DownloadProgressDelegate
      • DownloadProgressType
      • GitHub
      • GitHubActionsApi
      • GitHubPackage
      • GitHubPackageApi
      • GitHubPackageType
      • GitHubPackageVersion
      • GitHubPackageVisibility
      • GitHubReleaseApi
      • GitHubRepoPath
      • GitHubTagApi
      • IProfileClient
      • IProfileRequest
      • IProfileResponse
      • MaintainerProfile
      • NotifyClient
      • OnePassword
      • OnePasswordException
      • ProfileException
      • ProfileHandlerResult
      • ProfileRequest
      • ProfileResponse
      • ProfileServer
      • ProfileStatus
      • XenServer
    • Neon.Deployment.CodeSigning
      • AzureProfile
      • CodeSigner
      • UsbTokenProfile
    • Neon.Diagnostics
      • AssertException
      • ConfigExtensions
      • ConsoleJsonLogExporter
      • ConsoleJsonLogExporterOptions
      • ConsoleTextLogExporter
      • ConsoleTextLogExporterOptions
      • ExceptionInfo
      • FileLogExporter
      • FileLogExporterFormat
      • FileLogExporterOptions
      • LogAsTraceProcessor
      • LogAsTraceProcessorOptions
      • LogAttributeNames
      • LogAttributes
      • LogEvent
      • LogEventInterceptor
      • LoggerExtensions
      • NullLogger
      • TelemetryHub
      • TelemetrySpanEventNames
      • TelemetrySpanExtensions
    • Neon.Docker
      • DockerClient
      • DockerNetwork
      • DockerNetworkContainer
      • DockerNetworkIpam
      • DockerNode
      • DockerNodeManagerStatus
      • DockerResponse
      • DockerSettings
      • DockerVolume
      • NetworkCreateResponse
      • ServiceBindOptions
      • ServiceConfig
      • ServiceContainerSpec
      • ServiceCredentialSpec
      • ServiceDetails
      • ServiceDiscreteResourceSpec
      • ServiceDnsConfig
      • ServiceEndpoint
      • ServiceEndpointMode
      • ServiceEndpointPortConfig
      • ServiceEndpointSpec
      • ServiceFile
      • ServiceGenericResources
      • ServiceGlobalSchedulingMode
      • ServiceHealthCheck
      • ServiceIsolationMode
      • ServiceListResponse
      • ServiceLogDriver
      • ServiceMode
      • ServiceMount
      • ServiceMountBindPropagation
      • ServiceMountConsistency
      • ServiceMountType
      • ServiceNamedResourceSpec
      • ServiceNetwork
      • ServicePlacement
      • ServicePlacementPreferences
      • ServicePlacementSpreadSettings
      • ServicePlatform
      • ServicePortMode
      • ServicePortProtocol
      • ServicePrivileges
      • ServiceReplicatedSchedulingMode
      • ServiceResourceSettings
      • ServiceResources
      • ServiceRestartCondition
      • ServiceRestartPolicy
      • ServiceRollbackConfig
      • ServiceRollbackFailureAction
      • ServiceRollbackOrder
      • ServiceSELinuxContext
      • ServiceSchedulingMode
      • ServiceSecret
      • ServiceSpec
      • ServiceTaskTemplate
      • ServiceTmpfsOptions
      • ServiceUpdateConfig
      • ServiceUpdateFailureAction
      • ServiceUpdateOrder
      • ServiceUpdateState
      • ServiceUpdateStatus
      • ServiceVersion
      • ServiceVirtualIP
      • ServiceVolumeDriverConfig
      • ServiceVolumeOptions
      • VolumeListResponse
    • Neon.GitHub
      • GitExtensions
      • GitHubCredentials
      • GitHubRepo
      • LocalRepoApi
      • NoLocalRepositoryException
      • RemoteRepoApi
      • RemoteRepoBranchApi
      • RemoteRepoIssueApi
      • RemoteRepoIssueCommentApi
      • RemoteRepoPath
      • RemoteRepoReleaseApi
      • RemoteRepoTagApi
    • Neon.HyperV
      • HyperVClient
      • HyperVDriverType
      • HyperVException
      • NetAdapter
      • VirtualDrive
      • VirtualIPAddress
      • VirtualMachine
      • VirtualMachineNetworkAdapter
      • VirtualMachineState
      • VirtualNat
      • VirtualSwitch
      • VirtualSwitchType
    • Neon.IO
      • BlockStream
      • FixedLengthStream
      • IStaticDirectory
      • IStaticFile
      • LineEnding
      • LinuxPath
      • LinuxPermissions
      • PreprocessReader
      • RelayStream
      • StaticDirectoryBase
      • StaticFileBase
      • SubStream
      • TempFile
      • TempFolder
    • Neon.JsonConverters
      • JsonDateTimeConverter
      • JsonGenericConverter<T>
      • JsonNullableDateTimeConverter
    • Neon.ModelGen
      • ActionResult<T>
      • ApiVersion
      • ApiVersionAttribute
      • BodyStreamAttribute
      • ControllerValidationAttribute
      • DataModelAttribute
      • EnumMember
      • FromBodyAttribute
      • FromHeaderAttribute
      • FromQueryAttribute
      • FromRouteAttribute
      • GeneratedClientAttribute
      • GeneratedMethodAttribute
      • GeneratedParamAttribute
      • HashSourceAttribute
      • HttpAttribute
      • HttpDeleteAttribute
      • HttpGetAttribute
      • HttpHeadAttribute
      • HttpOptionsAttribute
      • HttpPatchAttribute
      • HttpPostAttribute
      • HttpPutAttribute
      • IActionResult
      • ModelGenerator
      • ModelGeneratorOutput
      • ModelGeneratorSettings
      • NoCodeGenAttribute
      • NoControllerValidationAttribute
      • PassAs
      • PersistableAttribute
      • PersistableKeyAttribute
      • RouteAttribute
      • ServiceModelAttribute
      • TargetAttribute
      • UxFrameworks
    • Neon.Net
      • HttpApiException
      • HttpException
      • JsonClient
      • JsonClientPayload
      • JsonResponse
      • Jwt
      • LocalHostSection
      • NetConst
      • NetHelper
      • NetworkCidr
      • NetworkConfiguration
      • NetworkException
      • NetworkPorts
      • Pinger
      • ReachableHost
      • ReachableHostMode
      • StreamDocument
    • Neon.Postgres
      • ConnectionExtensions
      • DatabaseStatus
      • PreparedCommand
      • ReaderAsyncEnumerator
      • ReaderEnumerator
      • ReaderExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
    • Neon.Retry
      • ExponentialRetryPolicy
      • IRetryPolicy
      • LinearRetryPolicy
      • NoRetryPolicy
      • RetryPolicy
      • RetryPolicyBase
      • RetryTransientArgs
      • TransientDetector
      • TransientException
    • Neon.Roslyn
      • DisplayFormat
      • DocumentationComment
      • DocumentationItem
      • MetadataLoadContext
      • RoslynAssembly
      • RoslynConstructorInfo
      • RoslynCustomAttributeData
      • RoslynExtensions
      • RoslynFieldInfo
      • RoslynMethodInfo
      • RoslynParameterInfo
      • RoslynPropertyInfo
      • RoslynType
      • SharedUtilities
    • Neon.Roslyn.Xunit
      • AdditionalSourceText
      • CompilationOptions
      • CompilationOptionsProvider
      • TestCompilation
      • TestCompilationAssertions
      • TestCompilationBuilder
      • TestCompilationBuilderExtensions
      • TestCompilationExtensions
    • Neon.SSH
      • CommandBundle
      • CommandFile
      • CommandResponse
      • HostFolders
      • IBashCommandFormatter
      • ILinuxSshProxy
      • LinuxDiskInfo
      • LinuxDiskPartition
      • LinuxSshProxy
      • LinuxSshProxy<TMetadata>
      • NamespaceDoc
      • RemoteCommandException
      • RunOptions
      • SshCredentials
      • SshExtensions
      • SshProxyException
    • Neon.Service
      • LogMetricsProcessor
      • MetricsMode
      • MetricsOptions
      • NeonService
      • NeonServiceOptions
      • NeonServiceStatus
      • OtelConfigExtensions
      • OtlpCollectorChecker
      • ProcessTerminator
      • ServiceApiContact
      • ServiceApiInfo
      • ServiceApiLicense
      • ServiceDependencies
      • ServiceDescription
      • ServiceEndpoint
      • ServiceEndpointProtocol
      • ServiceEndpoints
      • ServiceMap
    • Neon.SignalR
      • DependencyInjectionExtensions
      • DnsCache
      • GroupAction
      • GroupCommand
      • IDnsCache
      • Invocation
      • NatsHubLifetimeManager<THub>
      • ProxyConfig
      • ServiceCollectionExtensions
      • ServiceDiscovey
      • SignalrProxyMiddleware
      • SignalrProxyMiddlewareExtensions
      • TracerProviderBuilderExtensions
    • Neon.Tailwind
      • ClickOffEventHandler
      • ComponentEventArgs<TSender>
      • ComponentEventArgs<TSender, TEventArgs>
      • DisclosureState
      • EventHandlerComponentBase<TComponent>
      • HeadlessButton
      • HeadlessDialog
      • HeadlessDialogPanel
      • HeadlessDisclosure
      • HeadlessDisclosureButton
      • HeadlessDisclosurePanel
      • HeadlessListboxButton<TValue>
      • HeadlessListboxLabel<TValue>
      • HeadlessListboxOption<TValue>
      • HeadlessListboxOptions<TValue>
      • HeadlessListbox<TValue>
      • HeadlessMenu
      • HeadlessMenuButton
      • HeadlessMenuItem
      • HeadlessMenuItems
      • HeadlessSwitch
      • HeadlessSwitchGroup
      • HeadlessSwitchLabel
      • IPortalBinder
      • KeyDownEventHandler
      • KeyboardKey
      • ListboxFocus
      • ListboxState
      • MenuFocus
      • MenuState
      • Portal
      • PortalBinder
      • PortalContent
      • SearchAssistant
      • TailwindExtensions
      • Transition
      • TransitionGroup
      • TransitionState
    • Neon.Tasks
      • Async
      • AsyncAutoResetEvent
      • AsyncManualResetEvent
      • AsyncMutex
      • AsyncPeriodicTask
      • AsyncReaderWriterLock
      • AsyncReentrantMutex
      • AsyncTimer
      • IAsyncFuture
      • IAsyncFuture<T>
      • NonDisposableTask
      • NonDisposableTask<T>
      • SyncContext
      • SyncContextMode
    • Neon.Temporal
      • ActivityHelper
      • ActivityLogEnricher
      • TemporalEnricherTagNames
      • WorkflowLogEnricher
    • Neon.Time
      • GatedTimer
      • GoDuration
      • PolledTimer
      • RecurringTimer
      • RecurringTimerType
      • SysTime
      • TimeOfDay
    • Neon.WSL
      • Wsl2Proxy
    • Neon.Web
      • AesProtector
      • DataProtectionExtensions
      • NeonController
      • NeonControllerBase
      • RoundTripJsonInputFormatter
      • RoundTripJsonOutputFormatter
      • TracerProviderBuilderExtensions
      • WebHelper
    • Neon.WinTTY
      • ConsoleTTY
    • Neon.Windows
      • MEMORYSTATUSEX
      • PowerShellException
      • Win32
    • Neon.XenServer
      • IXenClient
      • XenClient
      • XenClient.MachineOperations
      • XenClient.StorageOperations
      • XenClient.TemplateOperations
      • XenException
      • XenHostInfo
      • XenObject
      • XenResponse
      • XenStorageRepository
      • XenTempIso
      • XenTemplate
      • XenVirtualDisk
      • XenVirtualMachine
      • XenVmPowerState
    • Neon.Xunit
      • AnsiblePlayResults
      • AnsiblePlayer
      • AnsibleTaskResult
      • AspNetFixture
      • BasicFixture
      • CodeFixture
      • CollectionComparer<T>
      • ComposedFixture
      • ContainerFixture
      • ContainerLimits
      • DockerComposeFixture
      • DockerFixture
      • DockerFixture.ConfigInfo
      • DockerFixture.ContainerInfo
      • DockerFixture.NetworkInfo
      • DockerFixture.SecretInfo
      • DockerFixture.ServiceInfo
      • DockerFixture.StackDefinition
      • DockerFixture.StackInfo
      • DockerFixture.StackService
      • EnvironmentFixture
      • HostsFixture
      • ITestFixture
      • IncompatibleServiceException
      • MaintainerFactAttribute
      • MaintainerTheoryAttribute
      • MockHttpServer
      • MockHttpServerExtensions
      • NatsFixture
      • NatsStreamingFixture
      • NeonServiceFixture<TService>
      • PlatformFactAttribute
      • RepeatAttribute
      • TargetPlatforms
      • TestArea
      • TestCollection
      • TestContext
      • TestFixture
      • TestFixtureStatus
      • TestHelper
      • TestHttpClient
      • TestOutputWriter
      • TestTrait
      • XunitExtensions
    • Neon.Xunit.YugaByte
      • YugaByteFixture
    • Neon.YugaByte
      • YugaByteHelper

    Class CommandLine

    Performs common operations on application a DOS or Linux command line.

    Inheritance
    object
    CommandLine
    Namespace: Neon.Common
    Assembly: Neon.Common.dll
    Syntax
    public sealed class CommandLine
    Remarks

    Command lines may consist of zero or more items. Items that begin with the dash (-) character are considered to be command line options. Items that begin with an at sign (@) can be considered to be response files, and all other items are considered to be command line arguments.

    note

    The "-" and "--" items (without an option name are considered arguments, not options.

    The static ExpandFiles(string[]) method can be used to process response files specified in a command line. Response files are specified by prepending a '@' character to the name of a text file and then treating each line of the file as a command line item.

    The static ExpandWildcards(string) method can be used to expand file names with wildcard characters into the set of actual files that match the pattern.

    The CommandLine class can also handles parsing of items as command line options.

    --<option name>[=<value>]
    

    You can also use single or double quotes around option values that include spaces or other special characters:

    --<option name>[='<value>'] --<option name>[="<value>"]

    will be parsed into name/value pairs and will be available for lookup via the string keyed indexer. Options that specify no value will be assigned an empty string value.

    note

    Command line option names are case sensitive.

    The class will also make all command line items available via the integer keyed indexer which will return items based on their position on the command line and also via the Items property. Command line items that are not command, are available via the Arguments property. Options can be looked up via the GetOption(string, string) and GetOptionValues(string) overrides.

    CommandLine also supports the definition of long and short forms of options with optional default values using the DefineOption(params string[]) method. This associates one or more option names with an optional default value.

    You can use this easily implement the short and long forms of options as well as to centralize the specification of option default values.

    var commandLine = new CommandLine(args);
    

    commandLine.DefineOption("-q", "--quiet"); commandLine.DefineOption("-k", "--key").Default = "none";

    // These calls both return the option value for "-q" or "--quiet". // Since no default value was set, the default value will be the // empty string.

    commandLine.GetOption("-q"); commandLine.GetOption("--quiet");

    // These calls both return the option value for "-k" or "--key". // The default value will be "none".

    commandLine.GetOption("-k"); commandLine.GetOption("--key");

    note

    This class assumes that the position of command line options doesn't matter, which is somewhat simplistic. In particular, the Shift(int, string) method actually relocates all of the options to the beginning of the shifted command line.

    Constructors

    CommandLine(params object[])

    Constructs an instance optionally expanding any response files specified in the arguments passed.

    Declaration
    public CommandLine(params object[] args)
    Parameters
    Type Name Description
    object[] args

    The optional command line arguments.

    Properties

    Arguments

    Returns the array of command line values (items that are not command line options).

    Declaration
    public string[] Arguments { get; }
    Property Value
    Type Description
    string[]

    HasHelpOption

    Determines if the --help command line option is present.

    Declaration
    public bool HasHelpOption { get; }
    Property Value
    Type Description
    bool

    true if the --help help option is present.

    this[int]

    Returns an item from the command line based on its position.

    Declaration
    public string this[int index] { get; }
    Parameters
    Type Name Description
    int index

    The zero-based position of the desired argument.

    Property Value
    Type Description
    string

    The argument string.

    Items

    Returns the array of command line arguments (including both command line options and values).

    Declaration
    public string[] Items { get; }
    Property Value
    Type Description
    string[]

    Options

    Returns the command line options as a dictionary of option name/value tuples.

    Declaration
    public Dictionary<string, string> Options { get; }
    Property Value
    Type Description
    Dictionary<string, string>

    Original

    Returns the original unshifted command line.

    Declaration
    public CommandLine Original { get; }
    Property Value
    Type Description
    CommandLine

    Methods

    DefineOption(params string[])

    Adds an option definition to the command line and returns the definition so its default value may be set if desired.

    Declaration
    public CommandLine.OptionDefinition DefineOption(params string[] names)
    Parameters
    Type Name Description
    string[] names

    The option names (e.g. the short and long form).

    Returns
    Type Description
    CommandLine.OptionDefinition

    The CommandLine.OptionDefinition.

    Remarks

    You can use this easily implement the short and long forms of options as well as to centralize the specification of option default values.

    var commandLine = new CommandLine(args);
    

    commandLine.DefineOption("-q", "--quiet"); commandLine.DefineOption("-k", "--key").Default = "none";

    // These calls both return the option value for "-q" or "--quiet". // Since no default value was set, the default value will be the // empty string.

    commandLine.GetOption("-q"); commandLine.GetOption("--quiet");

    // These calls both return the option value for "-k" or "--key". // The default value will be "none".

    commandLine.GetOption("-k"); commandLine.GetOption("--key");

    ExpandFiles(string[])

    Expands the command line by processing items beginning with '@' as input files.

    Declaration
    public static string[] ExpandFiles(string[] args)
    Parameters
    Type Name Description
    string[] args

    The command line arguments.

    Returns
    Type Description
    string[]

    The set of expanded items.

    Remarks

    Command line items will be assumed to specify a text file name after the '@'. This file will be read and each non-empty line of text will be inserted as a command line parameter.

    Lines of text whose first non-whitespace character is a pound sign (#) will be ignored as comments.

    Command line parameters may also span multiple lines by beginning the parameter with a line of text begininning with "{{" and finishing it with a line of text containing "}}". In this case, the command line parameter will be set to the text between the {{...}} with any CRLF sequences replaced by a single space.

    Here's an example:

    # This is a comment and will be ignored
    

    -param1=aaa -param2=bbb {{ -param3=hello world }}

    This will be parsed as three command line parameters: -param1=aaa, -param2=bbb, and -param3=hello world

    Exceptions
    Type Condition
    IOException

    Thrown if there's a problem opening an "@" input file.

    FormatException

    Thrown if there's an error parsing an "@" input file.

    ExpandWildcards(string)

    Checks the argument passed for wildcards and expands them into the appopriate set of matching file names.

    Declaration
    public static string[] ExpandWildcards(string path)
    Parameters
    Type Name Description
    string path

    The file path potentially including wildcards.

    Returns
    Type Description
    string[]

    The set of matching file names.

    Format(params object[])

    Formats an array of objects into a form suitable for passing to a process on the command line by adding double quotes around any values with embedded spaces.

    Declaration
    public static string Format(params object[] args)
    Parameters
    Type Name Description
    object[] args

    The arguments to be formatted.

    Returns
    Type Description
    string

    the formatted string.

    Exceptions
    Type Condition
    FormatException

    Thrown if any of the arguments contain double quote or any other invalid characters.

    GetArguments(int)

    Enumerates the command line arguments beginning at the specified index.

    Declaration
    public IEnumerable<string> GetArguments(int startIndex = 0)
    Parameters
    Type Name Description
    int startIndex

    The index of the first argument to be returned.

    Returns
    Type Description
    IEnumerable<string>

    The enumerated arguments.

    GetFlag(string)

    Determines whether an option is present on the command line.

    Declaration
    public bool GetFlag(string optionName)
    Parameters
    Type Name Description
    string optionName

    The case sensitive option name (including the leading dashes (-).

    Returns
    Type Description
    bool

    The option value if present, the specified default value otherwise.

    GetOption(string, string)

    Returns the value associated with a command line option if the option was present on the command line otherwise, the specified default value will be returned.

    Declaration
    public string GetOption(string optionName, string def = null)
    Parameters
    Type Name Description
    string optionName

    The case sensitive option name (including the leading dashes (-).

    string def

    The default value.

    Returns
    Type Description
    string

    The option value if present, the specified default value otherwise.

    Remarks

    If the optionName was included in a previous DefineOption(params string[]) call, then all aliases for the option will be searched. If the option is not present on the command line and def is null, then the default defined default value will be returned otherwise def will override the definition.

    GetOptionValues(string)

    Returns all of the values a command line option that appears multiple times in the command.

    Declaration
    public string[] GetOptionValues(string optionName)
    Parameters
    Type Name Description
    string optionName

    The case sensitive option name (including the leading dashes (-).

    Returns
    Type Description
    string[]

    The array of values found sorted in the same order thney appear in the command line.

    Remarks
    note

    Only command line options that actually specify a value using the colon (=) syntax are returned by this method.

    If the optionName was included in a previous DefineOption(params string[]) call, then all aliases for the option will be searched.

    HasOption(string)

    Determines if an option was present on the command line.

    Declaration
    public bool HasOption(string optionName)
    Parameters
    Type Name Description
    string optionName

    The case sensitive option name (including the leading dashes (-).

    Returns
    Type Description
    bool

    true if the option is present.

    Remarks

    If the optionName was included in a previous DefineOption(params string[]) call, then all aliases for the option will be searched.

    Parse(string)

    Parses the argument string passed into a CommandLine instance, dealing with quoted parameters, etc.

    Declaration
    public static CommandLine Parse(string input)
    Parameters
    Type Name Description
    string input

    The argument string.

    Returns
    Type Description
    CommandLine

    The parsed CommandLine.

    Preprocess(Dictionary<string, string>, Regex)

    Preprocesses the command line by using PreprocessReader to replace any environment variable, profile, or secret references in the command line arguments, like:

    $(env:VARIABLE) Replaced with the environment VARIABLE
    $(profile:VALUE) Replaced with the profile VALUE
    ${password:SECRET} Replaced with the password field of the SECRET
    ${password:SECRET:SOURCE} Replaced with the password field of the SECRET obtained from SOURCE
    ${password:SECRET[PROPERTY]} Replaced with the PROPERTY field of the SECRET
    ${password:SECRET[PROPERTY]:SOURCE} Replaced with the PROPERTY field of the SECRET obtained from SOURCE
    note

    IMORTANT: You'll probably need to surround variable references with single quotes on Linux to prevent Bash from interpreting these as Bash variables.

    note

    IMPORTANT: You must register an IProfileClient implementation with ServiceContainer for this to work.

    Declaration
    public CommandLine Preprocess(Dictionary<string, string> variables = null, Regex variableRegex = null)
    Parameters
    Type Name Description
    Dictionary<string, string> variables

    Optionally specifies variables to be incuded in the preprocessing.

    Regex variableRegex

    Optionally specifies the regular expression that will be used to locate and process any variable references. This defaults to CurlyVariableExpansionRegex but may be set to any expressions supported by PreprocessReader.

    Returns
    Type Description
    CommandLine

    A new CommandLine including any changes.

    Shift(int, string)

    Returns a new CommandLine which includes all of the command line options and the arguments starting at the position passed to the end of the command line, essentially shifting arguments to the left.

    Declaration
    public CommandLine Shift(int position, string splitter = "--")
    Parameters
    Type Name Description
    int position

    The index of the first argument to be included in the result.

    string splitter

    The optional argument used to ensure that we're only shifting the left side of a command line. This defaults to "--" but may be set to null or the empty string to disable this behavior.

    Returns
    Type Description
    CommandLine

    The new CommandLine.

    Split(string, bool)

    Splits the command line into two parts, the command line to the left of the first specified item (defaults to "--") and the command line to the right of it.

    Declaration
    public (CommandLine Left, CommandLine Right) Split(string splitter = "--", bool addSplitterToRight = false)
    Parameters
    Type Name Description
    string splitter

    The split item (defaults to "--").

    bool addSplitterToRight

    Optionally specifies that the split item should be included in the right command line returned.

    Returns
    Type Description
    (CommandLine Left, CommandLine Right)

    A tuple with Left and Right properties.

    Remarks
    note

    The Left command line will return with a copy of the original option definitions.

    note

    If there is no split item present, then Right will be null.

    StartsWithArgs(params string[])

    Determines whether the command line starts with the specified arguments.

    Declaration
    public bool StartsWithArgs(params string[] args)
    Parameters
    Type Name Description
    string[] args

    The non-null argument strings.

    Returns
    Type Description
    bool

    true if the command is prefxed with the specified arguments.

    Remarks
    note

    The argument comparison is case sensitive.

    ToFormatted(string, bool, bool, Redactor)

    Converts the command line into a nicely formatted (potentially multi-line) string suitable for including in logs.

    Declaration
    public string ToFormatted(string programName, bool withBars = false, bool withLineContinuation = false, CommandLine.Redactor redactor = null)
    Parameters
    Type Name Description
    string programName

    Specifies the program name.

    bool withBars

    Optionally include bars above and below the formatted command.

    bool withLineContinuation

    Optionally include line continuation characters appropriate for the current operating system.

    CommandLine.Redactor redactor

    Optionally passed as a redactor. See CommandLine.Redactor.

    Returns
    Type Description
    string

    The formatted string.

    ToString()

    Renders the command line as a string suitable for presenting to a process or a command line shell. Arguments that include spaces will be enclosed in double quotes.

    Declaration
    public override string ToString()
    Returns
    Type Description
    string

    The command line string.

    Overrides
    object.ToString()
    Exceptions
    Type Condition
    InvalidOperationException

    Thrown if a command line argument includes both single and double quotes.

    In this article
    Back to top © Copyright 2005-2023 by NEONFORGE LLC