asp.net Web API csv帮助程序写入流不起作用

时间:2019-03-10 08:19:37

标签: c# asp.net asp.net-web-api csvhelper

我的最初要求是让用户从对象列表中下载我找到此解决方案https://stackoverflow.com/a/49207997/11178128的文件

但是问题是当涉及到这一行

bin = stream.ToArray();

没有写入的流。因此,垃圾箱是一个空数组。 可能是什么问题?

另外,我正在通过Windows服务提供我的Web API。由于某种原因,System.Web.HttpContext.Current.Response给了我空值。知道为什么会这样吗? 预先感谢。

这是我到目前为止的代码,

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();
    }

3 个答案:

答案 0 :(得分:0)

这与另一个问题CsvHelper not writing anything to memory stream有关。 您只需要更改using语句,以便在调用StreamWriter

之前刷新stream.ToArray();
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();
    }

答案 1 :(得分:0)

实际上,经过一番挣扎之后,发现我错过了这一行。

textWriter.Flush();

如下面的答复中所述,我必须刷新textWriter对象才能写入文件。这是工作代码。

  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;

答案 2 :(得分:0)

 using (var ms = new MemoryStream())
            {
                using (var writer = new StreamWriter(ms))
                using (var csv = new CsvWriter(writer))
                {
                    csv.WriteRecords(dbresponse);
                } // the closing tag here is important!!It flush the streamwriter
                 ms.ToArray(); // or ms.GetBuffer()
            }

现在,ms.ToArray()将包含来自csvHelper的数据