title: C# - Check file size while writing - Change file in middle
body: <p>I am looping through directories and getting the files within
  While looping, I am writing the file's fullpath name to a file using a StreamWriter
  My problem is that I have to control the size of the file - it cant exceed 60K</p>
  
  <p>How can I accomplish this?</p>
  
  <p>I tried changing the streamwriter in the middle of the loop like this:</p>
  
  <pre><code>if (myPaths.Length &gt;= 60000)
  {
      outFile = "c:\\tag\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
      StreamWriter myStream = new StreamWriter(outFile);
  }    
  </code></pre>
  
  <p>But I am getting an error warning that I cant do this</p>
  
  <p>Here is my full code:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.IO;
  using System.Diagnostics;
  using Microsoft.Win32;
  using System.Globalization;
  using System.Windows.Forms;
  
  
  namespace ConsoleApplication1
  {
      class Program
      {
          static void Main(string[] args)
          {
              DirectoryInfo di = new DirectoryInfo("c:/myDir/");
          string outputFile = "c:\\dirA\\PathsFile.txt";
          StreamWriter sw = new StreamWriter(outputFile);
  
          string doneFile = "c:\\dirA\\ConfirmComplete.txt";
          if (File.Exists(doneFile)) File.Delete(doneFile);
  
          int ct = 0;
  
          ct = getAllFiles(di, "*.i", sw, outputFile);
  
          StreamWriter myDoneFile = new StreamWriter(doneFile);
          myDoneFile.AutoFlush = true;
          myDoneFile.WriteLine("Done");
          myDoneFile.WriteLine("Processed " + ct.ToString() + " files");
          myDoneFile.WriteLine("File Size = "+outputFile.Length.ToString());
      }
  
  
      static int getAllFiles(DirectoryInfo dir, string searchPattern, StreamWriter myStream, string outFile) 
      {
          var directories = dir.GetFiles(searchPattern, SearchOption.AllDirectories);
          int counter = 0;
          int FileCounter = 1;
          foreach (var file in directories)
          {
              if (file.FullName.Contains("\\BAK\\")) continue;
              myStream.WriteLine(file.FullName);
              counter += 1;
              FileInfo myPaths = new FileInfo(outFile);
              if (myPaths.Length &gt;= 60000)
              {
                  myStream.Close();
                  outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
                  StreamWriter myStream = new StreamWriter(outFile);
              }
          }
          return counter;
      }
  }
  </code></pre>
  
  <p>}   </p>
  
  <p>Any help would be appreciated
  I would gladly accept any enhancement ideas</p>
  
  <p>Thanks
  David</p>