File Class: Using Using Class Public Static Void
File Class: Using Using Class Public Static Void
using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; if (!File.Exists(path)) { using (StreamWriter sw = File.CreateText(path)) // Create a file to write to. { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } }\ using (StreamReader sr = File.OpenText(path)) // Open the file to read from. { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } try { string path2 = path + "temp"; // Ensure that the target does not exist. File.Delete(path2); File.Copy(path, path2); // Copy the file. Console.WriteLine("{0} was copied to {1}.", path, path2); File.Delete(path2); // Delete the newly created file. Console.WriteLine("{0} was successfully deleted.", path2); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } }
// Add some text to the file. sw.Write("This is the "); sw.WriteLine("header for the file."); sw.WriteLine("-------------------"); // Arbitrary objects can also be written to the file. sw.Write("The date is: "); sw.WriteLine(DateTime.Now); } } }
StreamReader Class
using System; using System.IO; class Test { public static void Main() { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("TestFile.txt")) { string line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }
using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; // Create the file if it exists. if (!File.Exists(path)) { // Create the file. using (FileStream fs = File.Create(path)) { Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file."); // Add some information to the file. fs.Write(info, 0, info.Length); } } // Open the stream and read it back. using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) { byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b,0,b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } try { // Try to get another handle to the same file. using (FileStream fs2 = File.Open(path, FileMode.Open)) { // Do some task here. } } catch (Exception e) { Console.Write("Opening the file twice is disallowed."); Console.WriteLine(", as expected: {0}", e.ToString()); } } } }