Tutorialsteacher

Follow Us

How to write texts to physical file using StreamWriter in C#?

Visit Stream I/O to know more about Stream and its class hierarchy.

The following example shows how StreamWriter makes it easy to write strings to a File:

Example: Write Text to File using StreamWriter
//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:DummyFile.txt");
        
//Open file for ReadWrite
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read ); 

//Create StreamWriter object to write string to FileSream
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Another line from streamwriter");
sw.Close();