Search code examples
c#asp.netasp.net-web-apicsvhelper

asp.net Web API csv helper writing to the stream doesn't work


My initial requirement is to let the user download a file from object list for that I found this solution https://stackoverflow.com/a/49207997/11178128,

But the problem is when it comes to this line

bin = stream.ToArray();

there are no streams written to it. So the bin comes as an empty array. What could be the problem?

Also, I'm making my web API available through a windows service. And for some reason System.Web.HttpContext.Current.Response gives me null. any idea why it can be? Thanks in advance.

This is the code i have so far

List<Device> devices;

    using (StreamReader r = new StreamReader(String.Format(@"{0}\deviceList.json", savefilePath)))
    {
      string json = r.ReadToEnd();
      devices = JsonConvert.DeserializeObject<List<Device>>(json);
    }

    byte[] bin;
    //String.Format(@"{0}\devices.csv", savefilePath)
    using (MemoryStream stream = new MemoryStream())
    using (TextWriter textWriter = new StreamWriter(stream))
    using (CsvWriter csv = new CsvWriter(textWriter))
    {
      csv.Configuration.ShouldQuote = (field, context) => false;

      csv.WriteRecords(devices);
      bin = stream.ToArray();
    }

Solution

  • Actually, after a bit of struggling, Found that i was missing this line.

    textWriter.Flush();
    

    As mentioned in the below reply I had to flush the textWriter object in order to write to the file. Here is the working code.

      byte[] data;
      using (MemoryStream stream = new MemoryStream())
      using (TextWriter textWriter = new StreamWriter(stream))
      using (CsvWriter csv = new CsvWriter(textWriter))
      {
        csv.Configuration.RegisterClassMap<DeviceMap>();
        csv.Configuration.ShouldQuote = (field, context) => false;
    
        csv.WriteRecords(values);
        textWriter.Flush();
        data = stream.ToArray();
      }
    
      return data;