如何从外部字符串文件创建数组



如何在语音识别程序中添加数组请参见下面的代码?我试过 使用StreamRead读取一个字符串并制作一个数组并将其放在commands.Add(new String[]后面,请参见下面的代码,但无法做到。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Globalization;
using System.IO;
    //Speech to Text 
       amespace CSharp_Speech_ConsoleApp
        {
        class Program
        {
         [DllImport("winmm.dll")]
         public static extern int waveInGetNumDevs();
         SpeechRecognitionEngine recognizer = new 
         SpeechRecognitionEngine(new      
         System.Globalization.CultureInfo("en-US"));   
         static void Main(string[] args)
         {
         // Make a Keywords array
         Choices commands = new Choices(); 
         //How to make this array  by importing strings from a file ? 
         commands.Add(new String[] { "Good morning.","Hello Mike.",
         "Good morning Eddy.","Good afternoon.","Good Evening","Hello",          
         "How are you", "Listen to me Mike", "Stop listening Mike!"
        });
             GrammarBuilder gBuilder = new GrammarBuilder();
             gBuilder.Append(commands);
             Grammar grammar = new Grammar(gBuilder);
             recogEngine.LoadGrammar(grammar);

         //get total number of sound input devices
          int waveInDevicesCount = waveInGetNumDevs(); 
          if(waveInDevicesCount == 0)
        {
            Console.WriteLine("No microphone detected.!");    
        }
        else
    {
            Console.WriteLine("Microphone detected. "); 
            recogEngine.SetInputToDefaultAudioDevice();
            recogEngine.SpeechRecognized += recogEngine_SpeechRecognized;
            recogEngine.RecognizeAsync(RecognizeMode.Multiple);
    }    
        Console.ReadLine();
       }
     // Console Display Speech Recognized result Text 
       static void recogEngine_SpeechRecognized(object sender,  
       SpeechRecognizedEventArgs e) 
    {
         string managedString = e.Result.Text;
         char[] st = managedString.ToCharArray();
         Console.WriteLine(st);
       }
      }
    }

如何通过从文件中导入字符串来制作数组?

这将为您提供文件中的所有行:

var lines = File.ReadAllLines(@"PathToYourFile");

上面的所有行从文件中读取到内存。还有另一种方法将按照您需要一一读一行:

var lines = File.ReadLines(@"PathToYourFile");

此返回IEnumerable<string>。例如,假设您的文件具有1000行,ReadAllLines将读取所有1000行的内存。但是ReadLines将根据需要阅读1 x 1。因此,如果这样做:

var lines = File.ReadLines(@"PathToYourFile");
var line1 = lines.First();
var lastLine = lines.Last();

即使您的文件具有1000行,它也只会将第一行和最后一行读取到内存中。

那么什么时候使用ReadLines方法?

假设您需要读取具有1000行的文件,而您对阅读感兴趣的唯一行是900至920,那么您可以这样做:

var lines = File.ReadLines(@"PathToYourFile");
var line900To920 = lines.Skip(899).Take(21);

最新更新