We can create a file in two different following methods
+ File.Create
+ File.CreateText
Nội dung
FileInfo.Create Method
The FileInfo.Create method creates a file at the given path. If just a file name is provided without a path, the file will be created in the current folder.
The following code snippet creates a file using the Create method that returns a FileSteam object. The Write method of FileStream can be used to write text to the file.
// Full file name string fileName = @"C:fileName.txt"; FileInfo fi = new FileInfo(fileName); try { // Check if file already exists. If yes, delete it. if (fi.Exists) { fi.Delete(); } // Create a new file using (FileStream fs = fi.Create()) { Byte[] txt = new UTF8Encoding(true).GetBytes("New file."); fs.Write(txt, 0, txt.Length); Byte[] author = new UTF8Encoding(true).GetBytes("Author CsharpCanBan.Com"); fs.Write(author, 0, author.Length); } // 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()); }
FileInfo.CreateText Method
The FileInfo.CreateText method creates and opens a file for writing UTF-8 encoded text. If 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.
// Full file name string fileName = @"C:TempMaheshTXFITx.txt"; FileInfo fi = new FileInfo(fileName); try { // Check if file already exists. If yes, delete it. if (fi.Exists) { fi.Delete(); } // Create a new file using (StreamWriter sw = fi.CreateText()) { sw.WriteLine("New file created: {0}", DateTime.Now.ToString()); sw.WriteLine("Author: CsharpCanBan.Com"); 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()); }