title: How to read data from database & write it on a txt file?
body: <p>I want to retrieve data from the server database using windows services on a text file?Can i do that?How will i do that?I mean i know to create a window service but i am confused with the SQL connection and  file writing part where to execute it?i have tried something</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          RunSchedule();
      }
      public static void RunSchedule()
      {
          string path = Path.GetFullPath("d:\\MyTest") + "\\" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
          try
          {
  
  
              if (!File.Exists(path))
              {
                  File.Create(path);
                  SqlConnection conn = new SqlConnection("Data Source=...;Initial Catalog=Test;User ID=s_a;Password=sa56ta112;");
                  String sql = @"SELECT Id,UserName, Email,Password,CreatedDate
                    FROM Register";
                  SqlCommand com = new SqlCommand();
                  com.CommandText = sql;
                  //com.Connection = conn;
                  conn.Open();
                  StreamWriter tw = File.AppendText("d:\\MyTest");
                  SqlDataReader reader = com.ExecuteReader();
                  tw.WriteLine("Id,UserName,Email,Password,CreatedDate");
                  while (reader.Read())
                  {
                      tw.Write(reader["Id"].ToString());
                      tw.Write(" , " + reader["UserName"].ToString());
                      tw.Write(" , " + reader["Email"].ToString());
                      tw.Write(" , " + reader["Password"].ToString());
                      tw.Write(" , " + reader["CreatedDate"].ToString());
                  }
                  tw.WriteLine(DateTime.Now);
                  tw.WriteLine("---------------------------------");
                  tw.Close();
                  reader.Close();
                  conn.Close();
              }
          }
          catch (Exception ex)
          {
              string errorLogPath = @"D:\MyTest.txt";
              File.AppendAllText(errorLogPath, Environment.NewLine + ex.Message);
          }
      }
  }
  </code></pre>
  
  <p>am i doing it correct? Please guide me.</p>