title: StreamWriter - Process cannot access the file because it is being used by another process
body: <p>I am trying to rewrite an <code>Add-Content</code> script as a <code>StreamWriter</code> version, reason being that the file is ~140 MB and <code>Add-Content</code> is far too slow.</p>
  
  <p>This is my <code>Add-Content</code> version, which loops through each row until it can find a header row starting <code>FILE|</code> and creates a new file with a filename of the second delimited (by pipe) value in that row.  The <code>Add-Content</code> works as intended, but is really slow.  It takes 35-40 mins to do it:</p>
  
  <pre><code>Param(
      [string]$filepath = "\\fileserver01\Transfer",
      [string]$filename = "sourcedata.txt"
  )
  
  $Path = $filepath
  $InputFile = (Join-Path $Path $filename)
  $Reader = New-Object System.IO.StreamReader($InputFile)
  
  while (($Line = $Reader.ReadLine()) -ne $null) {
      if ($Line -match 'FILE\|([^\|]+)') {
          $OutputFile = "$($matches[1]).txt"
      }
      Add-Content (Join-Path $Path $OutputFile) $Line
  }
  </code></pre>
  
  <p>I've researched that <code>StreamWriter</code> should be faster. Here is my attempt, but I get the error</p>
  
  <blockquote>
    <p>The process cannot access the file '\fileserver01\Transfer\datafile1.txt' because it is being used by another process.</p>
  </blockquote>
  
  <pre><code>Param(
      [string]$filepath = "\\fileserver01\Transfer",
      [string]$filename = "sourcedata.txt"
  )
  
  $Path = $filepath
  $InputFile = (Join-Path $Path $filename)
  $Reader = New-Object System.IO.StreamReader($InputFile)
  
  while (($Line = $Reader.ReadLine()) -ne $null) {
      if ($Line -match 'FILE\|([^\|]+)') {
          $OutputFile = "$($matches[1])"
      }
      $sw = New-Object System.IO.StreamWriter (Join-Path $Path $OutputFile)
      $sw.WriteLine($line)
  }
  </code></pre>
  
  <p>I assume it's something to do with using it in my loop. </p>
  
  <p>Sample data:</p>
  
  <pre>
  FILE|datafile1|25/04/17
  25044|0001|37339|10380|TT75
  25045|0001|37339|10398|TT75
  25046|0001|78711|15940|TT75
  FILE|datafile2|25/04/17
  25047|0001|98745|11263|TT75
  25048|0001|96960|13011|TT84
  FILE|datafile3|25/04/17
  25074|0001|57585|13639|TT84
  25075|0001|59036|10495|TT84
  FILE|datafile4|25/04/17
  25076|0001|75844|13956|TT84
  25077|0001|17430|01111|TT84
  </pre>
  
  <p>Desired outcome is 1 file per <code>FILE|</code> heade row using the second delimited value as the file name.</p>