テキスト ファイルを開いて、一度に 1 行ずつ読み込む方法を次のコード例に示します。 これを実行するには、System.IO 名前空間で定義される StreamReader クラスを使用します。 このクラスのインスタンスを使用してテキスト ファイルを開いてから、StreamReader.ReadLine メソッドを使用して各行を取得します。
このコードは、テキストを格納している textfile.txt という名前のファイル、または、「方法: テキスト ファイルを記述する (C++/CLI)」 で生成されたファイルで使用できます。
使用例
// text_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;
int main()
{
String^ fileName = "textfile.txt";
try
{
Console::WriteLine("trying to open file {0}...", fileName);
StreamReader^ din = File::OpenText(fileName);
String^ str;
int count = 0;
while ((str = din->ReadLine()) != nullptr)
{
count++;
Console::WriteLine("line {0}: {1}", count, str );
}
}
catch (Exception^ e)
{
if (dynamic_cast<FileNotFoundException^>(e))
Console::WriteLine("file '{0}' not found", fileName);
else
Console::WriteLine("problem reading file '{0}'", fileName);
}
return 0;
}