StreamWriter

You use a StreamWriter object to write data to a text file.
There are a number of ways you can obtain the StreamWriter object

System.IO.StreamWriter oStreamWriter; 
oStreamWriter = new System.IO.StreamWriter("C:\Temp\textfile.txt");

Using a FileStream

System.IO.StreamWriter oStreamWriter; 
System.IO.FileStream oFileStream;
oFileStream = new System.IO.FileStream("C:\Temp\textfile.txt", FileMode.Open);
oStreamWriter = new System.IO.StreamWriter(objFileStream);

Using a Stream
This lets you specify the mode, access and share

System.IO.StreamWriter oStreamWriter; 
System.IO.Stream oStream;
oStream = System.IO.File.Open("C:\Temp\textfile.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
oStreamWriter = new StreamWriter(objStream);

Using File.OpenWrite

System.IO.StreamWriter oStreamWriter; 
System.IO.FileStream oFileStream;
oFileStream = System.IO.File.OpenWrite("C:\Temp\textfile.txt");
oStreamWriter = new System.IO.StreamWriter(objFileStream);


Creating a Text File

File.CreateText

System.IO.StreamWriter oStreamWriter; 
oStreamWriter = System.IO.File.CreateText("C:\myfile.txt");
oStreamWriter.Write("this is some text");
oStreamWrite.Close;


Writing the Contents

There are several ways to write to a StreamWriter


Write a Single Line
This only works with strings and appends a newline character to the end.

string sText; 
oStreamWriter.WriteLine(sText);


© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext