Grammar Constructor (Stream, String)


Initializes a new instance of the Grammar class from a Stream and specifies a root rule.

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

public Grammar(
	Stream stream,
	string ruleName


Type: System.IO.Stream

A stream that describes a speech recognition grammar in a supported format.

Type: System.String

The identifier of the rule to use as the entry point of the speech recognition grammar, or null to use the default root rule of the grammar description.

Exception Condition

ruleName cannot be resolved or is not public, or ruleName is null and the grammar description does not define a root rule.


stream is null.


The stream 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.

To create a Grammar from a stream and specify a base URI to use to resolve relative rule references, use the Grammar constructor.

The following example loads a local SRGS file (cities.xml) from a file stream and specifies a rule to use as the root of the grammar. The content of the cities.xml file appears in the XML example that follows the C# example.

// Load a cities grammar from an I/O stream, use a specific
// rule as the root of the grammar, and return the new grammar. 
private static Grammar CreateGrammarFromStream2()
  FileInfo file = new FileInfo(@"c:\temp\cities.xml");
  Grammar citiesGrammar = new Grammar(file.OpenRead(), "Main");
  citiesGrammar.Name = "Stream Cities Grammar 2";
  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