The OpenWrite method opens a file for writing. If file does not exist, it creates a new file and opens if for writing. The OpenWrite method takes a file name as parameter and returns a FileStream object on the specified file.
FileStream fs = fi.OpenWrite();
Once we have a FileStream object, we can use its Write method to write to the file. The WriteMethod takes a byte array. The following code snippet creates a byte array and passes it to the Write method of the FileStream.
Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method n"); fs.Write(info, 0, info.Length);
The following lists the complete code sample.
string fileName = @"C:fileName.txt"; FileInfo fi = new FileInfo(fileName); // If file does not exist, create file if (!fi.Exists) { //Create the file. using (FileStream fs = fi.Create()) { Byte[] info = new UTF8Encoding(true).GetBytes("File Start"); fs.Write(info, 0, info.Length); } } try { // Open a file and add some contents to it using (FileStream fs = fi.OpenWrite()) { Byte[] info = new UTF8Encoding(true).GetBytes("New File using OpenWrite Method n"); fs.Write(info, 0, info.Length); info = new UTF8Encoding(true).GetBytes("----------START------------------------ n"); fs.Write(info, 0, info.Length); info = new UTF8Encoding(true).GetBytes("Author: Mahesh Chand n"); fs.Write(info, 0, info.Length); info = new UTF8Encoding(true).GetBytes("Book: ADO.NET Programming using C#n"); fs.Write(info, 0, info.Length); info = new UTF8Encoding(true).GetBytes("----------END------------------------"); fs.Write(info, 0, info.Length); } // Read file contents and display on the console using (FileStream fs = File.OpenRead(fileName)) { byte[] byteArray = new byte[1024]; UTF8Encoding fileContent = new UTF8Encoding(true); while (fs.Read(byteArray, 0, byteArray.Length) > 0) { Console.WriteLine(fileContent.GetString(byteArray)); } } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); }
NOTE:
A File must be opened using an IO resource before it can be read or write to. A file can be opened to read and/or write purpose. The FileInfo class provides four methods to open a file.
+ Open
+ OpenRead
+ OpenText
+ OpenWrite