1. in c++ environment
1 using namespace System; 2 using namespace System::IO; 3 int main() 4 { 5 try 6 { 7 // Create an instance of StreamReader to read from a file. 8 StreamReader^ sr = gcnew StreamReader( "TestFile.txt" ); 9 try 10 { 11 String^ line; 12 13 // Read and display lines from the file until the end of 14 // the file is reached. 15 while ( line = sr->ReadLine() ) 16 { 17 Console::WriteLine( line ); 18 } 19 } 20 finally 21 { 22 if ( sr ) 23 delete (IDisposable^)sr; 24 } 25 } 26 catch ( Exception^ e ) 27 { 28 // Let the user know what went wrong. 29 Console::WriteLine( "The file could not be read:" ); 30 Console::WriteLine( e->Message ); 31 } 32 }
2.c# environment
1 using System; 2 using System.IO; 3 4 class Test 5 { 6 public static void Main() 7 { 8 try 9 { 10 // Create an instance of StreamReader to read from a file. 11 // The using statement also closes the StreamReader. 12 using (StreamReader sr = new StreamReader("TestFile.txt")) 13 { 14 string line; 15 // Read and display lines from the file until the end of 16 // the file is reached. 17 while ((line = sr.ReadLine()) != null) 18 { 19 Console.WriteLine(line); 20 } 21 } 22 } 23 catch (Exception e) 24 { 25 // Let the user know what went wrong. 26 Console.WriteLine("The file could not be read:"); 27 Console.WriteLine(e.Message); 28 } 29 } 30 }
时间: 2024-10-21 17:46:32