using System.IO; FileStream file = new FileStream("path.txt", FileMode, FileAccess); FileMode -what the FileStream should do with the file: Append - Create - CreateNew - Open - OpenOrCreate - Truncate FileAccess - the file priveledges: - Read - ReadWrite - Write sw.Write("Hello file system world!"); sw.Close(); StreamReader - 4 options for reading from a file: - Read - ReadBlock - ReadLine - ReadToEnd FileStream file = new FileStream("path.txt", FileMode, FileAccess); StreamReader sr = new StreamReader(file); string s = sr.ReadToEnd(); sr.Close(); file.Close(); // *** Write to file *** // Specify file, instructions, and privelegdes FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write); // Create a new stream to write to the file StreamWriter sw = new StreamWriter(file); // Write a string to the file sw.Write("Hello file system world!"); // Close StreamWriter sw.Close(); // Close file file.Close(); // *** Read from file *** // Specify file, instructions, and privelegdes file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read); // Create a new stream to read from a file StreamReader sr = new StreamReader(file); // Read contents of file into a string string s = sr.ReadToEnd(); // Close StreamReader sr.Close(); // Close file file.Close(); ----------
Please note: make sure the file name follows the naming convention shown in the following example: Oct 19 2002 Minutes.doc
--- <%@ Page Language="C#" AutoEventWireup="True" Debug="true" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI" %> <%@ Import Namespace="System.Web.UI.WebControls" %> ---------------------------------------- http://msdn.microsoft.com/en-us/library/k3352a4t.aspx ---------------------------------------- Classes Used for File I/O Directory provides static methods for creating, moving, and enumerating through directories and subdirectories. The DirectoryInfo class provides instance methods. DirectoryInfo provides instance methods for creating, moving, and enumerating through directories and subdirectories. The Directory class provides static methods. DriveInfo provides instance methods for accessing information about a drive. File provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of a FileStream. The FileInfo class provides instance methods. FileInfo provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of a FileStream. The File class provides static methods. FileStream supports random access to files through its Seek method. FileStream opens files synchronously by default, but supports asynchronous operation as well. File contains static methods, and FileInfo contains instance methods. FileSystemInfo is the abstract base class for FileInfo and DirectoryInfo. Path provides methods and properties for processing directory strings in a cross-platform manner. DeflateStream provides methods and properties for compressing and decompressing streams using the Deflate algorithm. GZipStream provides methods and properties for compressing and decompressing streams. By default, this class uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats. SerialPort provides methods and properties for controlling a serial port file resource. File, FileInfo, DriveInfo, Path, Directory, and DirectoryInfo are sealed (in Microsoft Visual Basic, NotInheritable) classes. You can create new instances of these classes, but they cannot have derived classes. Classes Used for Reading from and Writing to Streams BinaryReader and BinaryWriter read and write encoded strings and primitive data types from and to Streams. StreamReader reads characters from Streams, using Encoding to convert characters to and from bytes. StreamReader has a constructor that attempts to ascertain what the correct Encoding for a given Stream is, based on the presence of an Encoding-specific preamble, such as a byte order mark. StreamWriter writes characters to Streams, using Encoding to convert characters to bytes. StringReader reads characters from Strings. StringReader allows you to treat Strings with the same API, so your output can be either a Stream in any encoding or a String. StringWriter writes characters to Strings. StringWriter allows you to treat Strings with the same API, so your output can be either a Stream in any encoding or a String. TextReader is the abstract base class for StreamReader and StringReader. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextReader are designed for Unicode character output. TextWriter is the abstract base class for StreamWriter and StringWriter. While the implementations of the abstract Stream class are designed for byte input and output, the implementations of TextWriter are designed for Unicode character input. Common I/O Stream Classes A BufferedStream is a Stream that adds buffering to another Stream such as a NetworkStream. (FileStream already has buffering internally, and a MemoryStream does not need buffering.) A BufferedStream can be composed around some types of streams in order to improve read and write performance. A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. A CryptoStream links data streams to cryptographic transformations. Although CryptoStream derives from Stream, it is not part of the System.IO namespace, but is in the System.Security.Cryptography namespace. A MemoryStream is a nonbuffered stream whose encapsulated data is directly accessible in memory. This stream has no backing store and might be useful as a temporary buffer. A NetworkStream represents a Stream over a network connection. Although NetworkStream derives from Stream, it is not part of the System.IO namespace, but is in the System.Net.Sockets namespace. ---------------------------------------- "c:\\MyDir\\MyFile.txt" in C#, or "c:\MyDir\MyFile.txt" in Visual Basic. "c:\\MyDir" in C#, or "c:\MyDir" in Visual Basic. "MyDir\\MySubdir" in C#, or "MyDir\MySubDir" in Visual Basic. "\\\\MyServer\\MyShare" in C#, or "\\MyServer\MyShare" in Visual Basic. -- using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { 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); // Copy the file. File.Copy(path, path2); Console.WriteLine("{0} was copied to {1}.", path, path2); // Delete the newly created file. File.Delete(path2); Console.WriteLine("{0} was successfully deleted.", path2); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } The following distinctions help clarify the differences between a file and a stream. A file is an ordered and named collection of a particular sequence of bytes having persistent storage. Therefore, with files, one thinks in terms of directory paths, disk storage, and file and directory names. In contrast, streams provide a way to write and read bytes to and from a backing store that can be one of several storage mediums. Just as there are several backing stores other than disks, there are several kinds of streams other than file streams. For example, there are network, memory, and tape streams. ---------- // directory listing: using System; using System.IO; class DirectoryLister { public static void Main(String[] args) { string path = Environment.CurrentDirectory; if (args.Length > 0) { if (Directory.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); } } ----- // read and write to a newly created file using System; using System.IO; class MyStream { private const string FILE_NAME = "Test.data"; public static void Main(String[] args) { // Create the new, empty data file. if (File.Exists(FILE_NAME)) { Console.WriteLine("{0} already exists!", FILE_NAME); return; } FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew); // Create the writer for data. BinaryWriter w = new BinaryWriter(fs); // Write data to Test.data. for (int i = 0; i < 11; i++) { w.Write( (int) i); } w.Close(); fs.Close(); // Create the reader for data. fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); // Read data from Test.data. for (int i = 0; i < 11; i++) { Console.WriteLine(r.ReadInt32()); } r.Close(); fs.Close(); } } ----------------- // open and append a 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(); } } ------- // read text 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); } } } -- // or -- 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(); } } ------ //write text 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); } } } -- //or -- 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(); } } } ----------- /* Use the GZipStream class to compress and decompress data. The following code example creates a file (test.txt) in the current directory, fills it with text, and displays the contents of the file to the console. The code then uses the GZipStream class to create a compressed version of the file (test.txt.gz) and compares the size of the two files. Finally, the code reads in the compressed file, decompresses it, and writes out a new file (test.txt.gz.txt) to the current directory. The code then displays the contents of the decompressed file. */ ---------- using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; public class CompressionSnippet { public static void Main() { string path = "test.txt"; // Create the text file if it doesn't already exist. if (!File.Exists(path)) { Console.WriteLine("Creating a new test.txt file"); string[] text = new string[] {"This is a test text file.", "This file will be compressed and written to the disk.", "Once the file is written, it can be decompressed", "using various compression tools.", "The GZipStream and DeflateStream class use the same", "compression algorithms, the primary difference is that", "the GZipStream class includes a cyclic redundancy check", "that can be useful for detecting data corruption.", "One other side note: both the GZipStream and DeflateStream", "classes operate on streams as opposed to file-based", "compression; data is read on a byte-by-byte basis, so it", "is not possible to perform multiple passes to determine the", "best compression method. Already compressed data can actually", "increase in size if compressed with these classes."}; File.WriteAllLines(path, text); } Console.WriteLine("Contents of {0}", path); Console.WriteLine(File.ReadAllText(path)); CompressFile(path); Console.WriteLine(); UncompressFile(path + ".gz"); Console.WriteLine(); Console.WriteLine("Contents of {0}", path + ".gz.txt"); Console.WriteLine(File.ReadAllText(path + ".gz.txt")); } public static void CompressFile(string path) { FileStream sourceFile = File.OpenRead(path); FileStream destinationFile = File.Create(path + ".gz"); byte[] buffer = new byte[sourceFile.Length]; sourceFile.Read(buffer, 0, buffer.Length); using (GZipStream output = new GZipStream(destinationFile, CompressionMode.Compress)) { Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name, destinationFile.Name, false); output.Write(buffer, 0, buffer.Length); } // Close the files. sourceFile.Close(); destinationFile.Close(); } public static void UncompressFile(string path) { FileStream sourceFile = File.OpenRead(path); FileStream destinationFile = File.Create(path + ".txt"); // Because the uncompressed size of the file is unknown, // we are using an arbitrary buffer size. byte[] buffer = new byte[4096]; int n; using (GZipStream input = new GZipStream(sourceFile, CompressionMode.Decompress, false)) { Console.WriteLine("Decompressing {0} to {1}.", sourceFile.Name, destinationFile.Name); n = input.Read(buffer, 0, buffer.Length); destinationFile.Write(buffer, 0, n); } // Close the files. sourceFile.Close(); destinationFile.Close(); } } -- ------------ using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; string path2 = path + "temp"; try { using (FileStream fs = File.Create(path)) {} // Ensure that the target does not exist. File.Delete(path2); // Copy the file. File.Copy(path, path2); Console.WriteLine("{0} copied to {1}", path, path2); // Try to copy the same file again, which should fail. File.Copy(path, path2); Console.WriteLine("The second Copy operation succeeded, which was not expected."); } catch (Exception e) { Console.WriteLine("Double copying is not allowed, as expected."); Console.WriteLine(e.ToString()); } } } // allow overwrite C# Copy Code using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; string path2 = path + "temp"; try { // Create the file and clean up handles. using (FileStream fs = File.Create(path)) {} // Ensure that the target does not exist. File.Delete(path2); // Copy the file. File.Copy(path, path2); Console.WriteLine("{0} copied to {1}", path, path2); // Try to copy the same file again, which should succeed. File.Copy(path, path2, true); Console.WriteLine("The second Copy operation succeeded, which was expected."); } catch { Console.WriteLine("Double copy is not allowed, which was not expected."); } } } --- //file.create --- using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; try { // Delete the file if it exists. if (File.Exists(path)) { // Note that no lock is put on the // file and the possibility exists // that another process could do // something with it between // the calls to Exists and Delete. File.Delete(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 (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } } } -- //file.move --- using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; string path2 = @"c:\temp2\MyTest.txt"; try { if (!File.Exists(path)) { // This statement ensures that the file is created, // but the handle is not kept. using (FileStream fs = File.Create(path)) {} } // Ensure that the target does not exist. if (File.Exists(path2)) File.Delete(path2); // Move the file. File.Move(path, path2); Console.WriteLine("{0} was moved to {1}.", path, path2); // See if the original exists now. if (File.Exists(path)) { Console.WriteLine("The original file still exists, which is unexpected."); } else { Console.WriteLine("The original file no longer exists, which is expected."); } } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } -- using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; // This text is added only once to the file. if (!File.Exists(path)) { // Create a file to write to. string[] createText = { "Hello", "And", "Welcome" }; File.WriteAllLines(path, createText); //File.WriteAllText(path, createText); } // This text is always added, making the file longer over time // if it is not deleted. string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText(path, appendText); //File.AppendAllText(path, appendText); // Open the file to read from. string[] readText = File.ReadAllLines(path); //string readText = File.ReadAllText(path); //Console.WriteLine(readText); foreach (string s in readText) { Console.WriteLine(s); } } } using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; // This text is added only once to the file. if (!File.Exists(path)) { // Create a file to write to. string createText = "Hello and Welcome" + Environment.NewLine; File.WriteAllText(path, createText); } // This text is always added, making the file longer over time // if it is not deleted. string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText(path, appendText); // Open the file to read from. string readText = File.ReadAllText(path); Console.WriteLine(readText); } } ---- //filestream ------ using System; using System.IO; using System.Text; using System.Security.AccessControl; namespace FileSystemExample { class FileStreamExample { public static void Main() { try { // Create a file and write data to it. // Create an array of bytes. byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data."); // Specify an access control list (ACL) FileSecurity fs = new FileSecurity(); fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow)); // Create a file using the FileStream class. FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs); // Write the number of bytes to the file. fWrite.WriteByte((byte)messageByte.Length); // Write the bytes to the file. fWrite.Write(messageByte, 0, messageByte.Length); // Close the stream. fWrite.Close(); // Open a file and read the number of bytes. FileStream fRead = new FileStream("test.txt", FileMode.Open); // The first byte is the string length. int length = (int)fRead.ReadByte(); // Create a new byte array for the data. byte[] readBytes = new byte[length]; // Read the data from the file. fRead.Read(readBytes, 0, readBytes.Length); // Close the stream. fRead.Close(); // Display the data. Console.WriteLine(Encoding.ASCII.GetString(readBytes)); Console.WriteLine("Done writing and reading data."); } catch (Exception e) { Console.WriteLine(e); } Console.ReadLine(); } } } --- IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException EndOfStreamException FileNotFoundException FileLoadException PathTooLongException