Visual C++ .NET/File Directory/StreamReader

Материал из .Net Framework эксперт
Версия от 12:05, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating a StreamReader class is with static methods of the File class

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
int main()
{
   String^ filename = "textfile.txt";
   try
   {
      StreamReader^ sr2 = File::OpenText(filename);
      String^ line;
      while ((line = sr2->ReadLine()) != nullptr)
      {
         Console::WriteLine(line);
      }
   }
   catch(IOException^ e)
   {
       Console::WriteLine("Exception! {0}", e->Message );
   }
}


Read each line of a text file and write it out to the console.

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
int main()
{
   String^ filename = "textfile.txt";
   try
   {
      StreamReader^ sr2 = File::OpenText(filename);
      String^ line;
      while ((line = sr2->ReadLine()) != nullptr)
      {
         Console::WriteLine(line);
      }
   }
   catch(IOException^ e)
   {
       Console::WriteLine("Exception! {0}", e->Message );
   }
}


Read text file line by line

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
int main()
{
   StreamWriter^ sw = gcnew StreamWriter("textfile.txt");
   sw->WriteLine("asdf");
   sw->Flush();
   sw->Close();
   StreamWriter^ sw2 = File::CreateText("newtextfile.txt");
   StreamReader^ sr = gcnew StreamReader("textfile.txt");
   String^ line;
   while ((line = sr->ReadLine()) != nullptr)
   {
      Console::WriteLine(line);
   }
}


Read text file with StreamReader

 
#include "stdafx.h"
using namespace System;
using namespace System::IO;
int main()
{
   StreamWriter^ sw = gcnew StreamWriter("textfile.txt");
   sw->WriteLine("asdf");
   sw->Flush();
   sw->Close();
   StreamWriter^ sw2 = File::CreateText("newtextfile.txt");
   StreamReader^ sr = gcnew StreamReader("textfile.txt");
   String^ line;
   while ((line = sr->ReadLine()) != nullptr)
   {
      Console::WriteLine(line);
   }
}