Introduction
In this article, we will learn about File.CreateText method in C#.
File.CreateText Method in C#
The File.CreateText method creates and opens a file for writing UTF-8 encoded text. If the file already exists, this method opens the file.
The following code snippet creates a file using the CreateText method that returns a StreamWriter object. The WriteLine method of SteamLine can be used to add line text to the object and writes to the file.
Syntax
- // Full file name
- string fileName = @"C:\Temp\MaheshTX.txt";
- try
- {
- // Check if file already exists. If yes, delete it.
- if (File.Exists(fileName))
- {
- File.Delete(fileName);
- }
- // Create a new file
- using (StreamWriter sw = File.CreateText(fileName))
- {
- sw.WriteLine("New file created: {0}", DateTime.Now.ToString());
- sw.WriteLine("Author: Mahesh Chand");
- sw.WriteLine("Add one more line ");
- sw.WriteLine("Add one more line ");
- sw.WriteLine("Done! ");
- }
- // Write file contents on console.
- using (StreamReader sr = File.OpenText(fileName))
- {
- string s = "";
- while ((s = sr.ReadLine()) != null)
- {
- Console.WriteLine(s);
- }
- }
- }
- catch (Exception Ex)
- {
- Console.WriteLine(Ex.ToString());
- }
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
Directory.GetCurrentDirectory Method
This Method is used the Gets the current working directory of the application.
Syntax
- public static string GetCurrentDirectory ();
The following example demonstrates how to use the GetCurrentDirectory method.
- using System;
- using System.IO;
- class Test
- {
- public static void Main()
- {
- try
- {
- // Get the current directory.
- string path = Directory.GetCurrentDirectory();
- string target = @"c:\temp";
- Console.WriteLine("The current directory is {0}", path);
- if (!Directory.Exists(target))
- {
- Directory.CreateDirectory(target);
- }
- // Change the current directory.
- Environment.CurrentDirectory = (target);
- if (path.Equals(Directory.GetCurrentDirectory()))
- {
- Console.WriteLine("You are in the temp directory.");
- }
- else
- {
- Console.WriteLine("You are not in the temp directory.");
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
- }
- }
Common I/O Tasks
The System.IO namespace provides several classes that allow for various actions, such as reading and writing, to be performed on files, directories, and streams. For more information, see File and Stream I/O.
Summary
In this article, we learned about File.CreateText method in C#.

Join the conversation! Your thoughts help the community grow.