Grammar Constructor (String)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Initializes a new instance of the Grammar class from a file.

Namespace:   System.Speech.Recognition
Assembly:  System.Speech (in System.Speech.dll)

public Grammar(
	string path


Type: System.String

The path of the file that describes a speech recognition grammar in a supported format.

Exception Condition

path contains the empty string (""), or the file describes a grammar that does not contain a root rule.


path is null.


The file does not contain a valid description, or describes a grammar that contains a rule reference that cannot be resolved.

This constructor does not pass any parameters to the initialization handler, and the description should not define an initialization handler that requires arguments.

This constructor can create a Grammar instance from the following formats:

This constructor compiles XML-format grammar files to a binary format to optimize them for loading and consumption by a speech recognition engine. You can reduce the amount of time required to construct a Grammar object from an XML-format grammar by compiling the grammar in advance, using one of the Compile methods.

An SRGS grammar can define a root rule. To create a Grammar object from a string and specify a root rule, use the Grammar constructor.

To create a Grammar object that specifies a base URI to use to resolve relative rule references, open the file in a file stream and use the Grammar.Grammar constructor.

The following example loads a speech recognition grammar from a local SRGS file to build a Grammar object. The content of the cities.xml file appears in the XML example that follows the C# example.

// Load a cities grammar from a local file and
// return the new grammar. 
private static Grammar CreateGrammarFromFile()
  Grammar citiesGrammar = new Grammar(@"c:\temp\cities.xml");
  citiesGrammar.Name = "SRGS File Cities Grammar";
  return citiesGrammar;

<?xml version="1.0" encoding="UTF-8" ?>
<grammar version="1.0" xml:lang="en-US"
         tag-format="semantics/1.0" root="Main">

  <!-- cities.xml: 
    Defines an SRGS grammar for requesting a flight. This grammar includes
    a Cities rule that lists the cities that can be used for departures
    and destinations. -->

  <rule id="Main">
      I would like to fly from <ruleref uri="#Cities"/>
      to <ruleref uri="#Cities"/>

  <rule id="Cities" scope="public">
      <item>Los Angeles</item>
      <item>New York</item>

.NET Framework
Available since 3.0
Return to top