简体   繁体   中英

Using TextWriter to write text files with parametric fileName

I have to write some text on text file using TextWriter .

My code is as follows:

static void Main(string[] args)
{
   List<int> _list_1 = new List<int>() { 1, 2, 3, 4 };
   List<int> _list_2 = new List<int>() { 5, 6, 7, 8 };
   var _year = 2005;
   var _root = @"C:\Users\~\Results";
   var _path = Path.Combine(_root, _year.ToString());
   var _testFile = _year.ToString() + " - IntegerLists.txt";
   _path = Path.Combine(_root, _year.ToString());

   if (!Directory.Exists(_path))
   {
      Directory.CreateDirectory(_path);
   }

   Console.WriteLine("Writing lists on text file...");
   TextWriter _tw = File.CreateText(Path.Combine(_path, _testFile));

   for ( int _i = 0; _i < _list_1.Count; _i++ )
   {
      _tw.WriteLine("List - 1 : {0}, List - 2 : = {1}", _list_1[_i], _list_2[_i]);
   }

   Console.WriteLine("Lists have been written on text file.");
   Console.ReadLine();
}  

It created the text file at specified path but there are no values in that text file. I got an empty file.

How to write text using TextWriter ?

You have to either Dispose or call Flush on the TextWriter instance. (See File.CreateText Method )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM