2012-03-30 14 views
1

ファイルを選択するウィンドウを開くためにボタンを作成した後、私は、実際のファイルから、またはmystreamというストリームから数値を抽出する方法を知らない。テキストファイルから数値を抽出する方法

Stream myStream; 
OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

openFileDialog1.InitialDirectory = "c:\\" ; 
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; 
openFileDialog1.FilterIndex = 2 ; 
openFileDialog1.RestoreDirectory = true ; 

if(openFileDialog1.ShowDialog() == DialogResult.OK) 
{ 
    if((myStream = openFileDialog1.OpenFile())!= null) 
    { 
//Problem here: How do i extract the numerical values from my txt file or the stream called mystream. 
// Insert code to read the stream here. 

     myStream.Close(); 
    } 
} 
+5

...? –

+8

入力ファイルを表示する –

+0

'StreamReader'を使って' myStream'を読み込み、 '.ReadLine()'と 'int.Parse'を呼び出すことができます。 – Marlon

答えて

4

まあ、我々は(私はこれを書いている時のような)あなたの入力フォーマットを知らないので、それは数字を取得するために正確に何をすべきか、あなたを伝えるのは難しいです。どのような形式で

しかし、ここでは、ファイルの各行を読み取るための一般的な要点だ...

if(openFileDialog1.ShowDialog() == DialogResult.OK) 
{ 
    if((myStream = openFileDialog1.OpenFile())!= null) 
    { 
     using (var reader = new StreamReader(myStream)) 
     { 
      string line; 

      while ((line = reader.ReadLine()) != null) 
      { 
       // if it's one num per line, you can use Parse() or TryParse() 
       var num = int.Parse(line); 

       // otherwise, you can use something like string.Split() or RegEx... 
      } 
     } 
    } 
} 
+0

-1答えはありません。 OPがあなたの答えを受け入れる場合、私にダウンボートをキャンセルするように伝えます。 –

+1

@ L.Bこれはテキストファイルなので、数値はテキスト形式にバインドされています。 'int.Parse'が適用され、この答えも同様です。 – Marlon

+0

@Marlonしたがって、すべての行に1つのintが含まれていることを確認できます。 –

関連する問題