Você está na página 1de 10

File Class

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()); } } }

How to: Create a Directory Listing


using System; using System.IO; class DirectoryLister { public static void Main(String[] args) { string path = "."; if (args.Length > 0) { if (File.Exists(args[0]) { path = args[0]; } else { Console.WriteLine("{0} not found; using current directory:", args[0]); } DirectoryInfo dir = new DirectoryInfo(path); foreach (FileInfo f in dir.GetFiles("*.exe")) { String name = f. Name; long size = f.Length; DateTime creationTime = f.CreationTime; Console.WriteLine("{0,-12:N0} {1,-20:g} {2}", size, creationTime, name); } } }

How to: Open and Append to a Log File


using System; using System.IO; class DirAppend { public static void Main(String[] args) { using (StreamWriter w = File.AppendText("log.txt")) { Log ("Test1", w); Log ("Test2", w); // Close the writer and underlying file. w.Close(); } // Open and read the file. using (StreamReader r = File.OpenText("log.txt")) { DumpLog (r); } } public static void Log (String logMessage, TextWriter w) { w.Write("\r\nLog Entry : "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(" :"); w.WriteLine(" :{0}", logMessage); w.WriteLine ("-------------------------------"); // Update the underlying file. w.Flush(); } public static void DumpLog (StreamReader r) { // While not at the end of the file, read and write lines. String line; while ((line=r.ReadLine())!=null) { Console.WriteLine(line); } r.Close(); }

How to : Read Text from a File


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); } } }

How to : Read Text from a File


using System; using System.IO; public class TextFromFile { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist.", FILE_NAME); return; } using (StreamReader sr = File.OpenText(FILE_NAME)) { String input; while ((input=sr.ReadLine())!=null) { Console.WriteLine(input); } Console.WriteLine ("The end of the stream has been reached."); sr.Close(); } }

How to: Write Text to a File


using System; using System.IO; class Test { public static void Main() { // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. using (StreamWriter sw = new StreamWriter("TestFile.txt")) {

// 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); } } }

How to: Write Text to a File


using System; using System.IO; public class TextToFile { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (File.Exists(FILE_NAME)) { Console.WriteLine("{0} already exists.", FILE_NAME); return; } using (StreamWriter sw = File.CreateText(FILE_NAME)) { sw.WriteLine ("This is my file."); sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 1, 4.2); sw.Close(); } } }

How to: Write Characters to a String


using System; using System.IO; using System.Text; public class CharsToStr { public static void Main(String[] args) { // Create an instance of StringBuilder that can then be modified. StringBuilder sb = new StringBuilder("Some number of characters"); // Define and create an instance of a character array from which // characters will be read into the StringBuilder. char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'}; // Create an instance of StringWriter // and attach it to the StringBuilder. StringWriter sw = new StringWriter(sb); // Write three characters from the array into the StringBuilder. sw.Write(b, 0, 3); // Display the output. Console.WriteLine(sb); // Close the StringWriter. sw.Close(); } }

Basic File I/O

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); } } }

File.Open Method (String, FileMode, FileAccess, FileShare)


Syntax:
public static FileStream Open( string path, FileMode mode, FileAccess access, FileShare share )

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()); } } } }

Você também pode gostar