I am using following code. It displays date and time for each file in log. But I want it to display only once

sw.WriteLine("File Name {0}", file);                            
sw.Write("\r\nLog Entry : ");
sw.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
sw.WriteLine ("-------------------------------");

The output is

Log File :
File Name D:\DotNet\test\1.txt

Log Entry : 12:47:05 PM Saturday, September 21, 2013

File Name D:\DotNet\test\1.xhtml

Log Entry : 12:47:05 PM Saturday, September 21, 2013

File Name D:\DotNet\test\1_2.xhtml

Log Entry : 12:47:05 PM Saturday, September 21, 2013

File Name D:\DotNet\test\1_3.xhtml

Log Entry : 12:47:05 PM Saturday, September 21, 2013

File Name D:\DotNet\test\1_4.xhtml

Log Entry : 12:47:05 PM Saturday, September 21, 2013

File Name D:\DotNet\test\1_5.xhtml

I want output as...

Log File :
File Name D:\DotNet\test\1.txt
File Name D:\DotNet\test\1.xhtml
File Name D:\DotNet\test\1_2.xhtml
File Name D:\DotNet\test\1_3.xhtml
File Name D:\DotNet\test\1_4.xhtml
File Name D:\DotNet\test\1_5.xhtml

Log Entry : 12:47:05 PM Saturday, September 21, 2013

please help me
thanks in advance

using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\Logfile.txt", true))
{
  sw.Write("\r\nLog File : ");

  foreach (string file in System.IO.Directory.GetFiles(@"C:\\files"))
  {
    sw.WriteLine("File Name {0}", file);
  }

  sw.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());

 }     

To get the format you need you have to get the file names within the loop and do the additional editing outside the loop.

Output :
Log File :
File Name C:\files\file 1.txt
File Name C:\files\file 2.txt
File Name C:\files\file 3.txt
File Name C:\files\file 4.txt
File Name C:\files\file 5.txt
2:50:20 PM Saturday, September 21, 2013

commented: Nice answer +14

thanks ....... it helped me a lot

The above code helped me a lot and at the same time different log files have to be created
i.e Logfile.txt, Logfile_1.txt, Logfile_2.txt

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.