title: How do I properly use StreamWriter when making multiple POST requests
body: <p>I have a program that posts multiple transactions to an API, on average about 40/50 transactions per day and the program runs once daily (as a job). I am getting an error <em><strong>'Cannot write to a closed TextWriter'</strong></em> when the flow tries to loop through the second record. Only the first transaction is being posted but when the loop attempts second record the program <em><strong>either crashes</strong></em> or throws error <em><strong>'Cannot write to a closed TextWriter'</strong></em>.</p>
  <p>Program.cs</p>
  <pre><code>  List&lt;Root2&gt; details = GetRemmitances();
          var httpWebRequest = (HttpWebRequest)WebRequest.Create(&quot;https://api.myloan.co.za/api/v1/inbound/create&quot;);
          ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
          httpWebRequest.ContentType = &quot;application/json&quot;;
          httpWebRequest.Headers.Add(&quot;x-api-key&quot;, Helpers.apikey.ToString());
          httpWebRequest.Method = &quot;POST&quot;;
          httpWebRequest.Timeout = 300000;
  
          using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
          {
  
              try
              {
                  foreach (var tran in details)
                  {
                      jsonRecord = JsonConvert.SerializeObject(tran);
                      
                  }
                  Console.WriteLine(jsonRecord);
                  streamWriter.Write(jsonRecord);
                  streamWriter.Flush();
                  streamWriter.Close();
                  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  
                      using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                      {
                          result = streamReader.ReadToEnd();
                          if (!File.Exists(filePath))
                          {
                              File.Create(filePath).Dispose();
                          }
                          using (stream = File.AppendText(filePath))
                          {
                          stream.WriteLine(result);
                          stream.Flush();
                          stream.Close();
                          }
                      }
                     
                
              }
              catch (WebException ex)
              {
                  ExceptionLogger.SendErrorToText(ex);
              }
            
          }  
  </code></pre>
  <p>Having done some searching I have removed  <code>stream.Close();</code> and <code>streamWriter.Close();</code> but this doesnt help either as the program continues to crash without throwing an error. I know that the using block also closes the TextWriter by definition so I have taken out all the logic out of the for loop as below :</p>
  <pre><code> FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);            
          StreamWriter sw = new StreamWriter(fs);
          StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
          var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
          StreamReader sr = new StreamReader(httpResponse.GetResponseStream());
          result = sr.ReadToEnd();
          foreach (var tran in details)
          {
              jsonRecord = JsonConvert.SerializeObject(tran);
              Console.WriteLine(jsonRecord);
              streamWriter.Write(jsonRecord);
              streamWriter.Flush();
              sw.WriteLine(result);
              sw.Flush();
          } 
         sw.Close();
         streamWriter.Close();  
  </code></pre>
  <p>This time I am getting error <strong>&quot;400 Bad Request&quot;</strong> despite that I am not posting a duplicate record (the upstream API doesnt accept duplicates and throws 400 Bad Request for such).</p>
  <p>I am not sure if the refactor is entirely correct or how to change the original implementation if need be.</p>
  <p>What am I missing?</p>