下面的代码示例演示如何打开并读取文本文件(每次读取一行)。 此项操作通过使用 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;
}