Either Read or write data to file is often needed in data migration or integration process between two computer systems. There are various ways to write text to a file in C#.

The tutorial below shows you how to write data to text file in Visual Studio C#.net. We will use StreamWriter.Write() method for writing text to a stream.

As example, we will write two data fields (days number and days name) with “,” delimiter to specify the boundary between separate of data fields.

The below is the user interface with File name (Label), File path(Text Box), Find (Button), Write (Button), Result (Label) and ofdBrowser (OpenFileDialog).

Step 1: Add using System.IO system namespace into the code

Step 2: Add code in the Find Button with click Event to pop up Windows dialog box (OpenFileDialog) for browsing and selecting files. Once selected, place the file name and path into txtFileName(Text Box).

Step 3: Add code in Write Button with click Event for write a string array into text file. Separate the data with “,” delimiter.

Step 4: The text file will be generated as below.