title: When i try to use thread to rename my file name and close and flush the FileStream , it will give me error Cannot access a closed file
body: <p>I have large amount of data, i need to make  '.txt' file in every 5 sec and write next coming data in that newly created '.txt' file but when i try to use Timer thread for that for sometime program run properly but after sometime it will through exception cannot access a closed file . Please help me in my code and suggest me what has to be done.</p>
  
  <pre><code>public class Program
      {
          public static void Main(string[] args)
          {
              Service s = new Service();
              s.init();
          }
      }
  
  
      class Service
      {
          FileStream fs = null;
          int filecount = 0;
          long a = 1000000000000000;
        // int j = 0;
  
          public void  init()
          {
              initialiseFile(filecount);
              timer();
              WriteINFile();
          }
  
          private void initialiseFile( int filecount)
          {
  
                  fs = File.Create("C:\\Users\\yogesh.ghonate\\source\\repos\\ConsoleApp3\\ConsoleApp3\\NewFolder1\\Index_" + filecount + ".txt");        
          }
          private void WriteINFile()
          {
              string sen = " write in file ";
  
                  for (int i = 0; i &lt; a; i++)
                  {
                      Byte[] title = new UTF8Encoding(true).GetBytes(sen);
  
                      fs.Write(title, 0, title.Length);
                  }
          }
  
          public void timer()
          {
              System.Timers.Timer th = new System.Timers.Timer();
              th.Interval = 5000;
              th.Elapsed += new ElapsedEventHandler(run);
              th.Start();         
              run(th, null);
          }
  
          public void run(object state, ElapsedEventArgs e)
          {
              Commitzfile();
          }
  
          private void Commitzfile()
          {
  
              //Stopwatch stopwatch = new Stopwatch();
              //stopwatch.Start();
              fs.Flush();
              fs.Close();
              // fs.Dispose();
              //stopwatch.Stop();
              filecount++;
              initialiseFile(filecount);
  
          }
      }
  </code></pre>