I need to read a fixed width file, map the records to another type and then write that data to a csv stream. I'm trying to use FileHelpers to do so but the WriteStream doesn't seem to write any data to the stream.
FixedWidthType.cs (the type to read)
[FixedLengthRecord, IgnoreFirst(2), IgnoreLast(1)]
public class FixedWidthType
{
[FieldFixedLength(6), FieldTrim(TrimMode.Right)]
public string BranchCode { get; set; }
// ...
}
CsvType.cs (the type to write)
[DelimitedRecord("|")]
public class CsvType
{
public string BranchCode { get; set; }
// ...
}
Program.cs
var readerEngine = new FileHelperEngine<FixedWidthType>();
var writerEngine = new FileHelperEngine<CsvType>();
var file = File.ReadAllBytes("fixedWidthFile.txt");
using (var sr = new MemoryStream(file))
using (var reader = new StreamReader(sr))
using (var sw = new MemoryStream())
using (var writer = new StreamWriter(sw))
{
// read fixedwidth data
var fixedWidthRecords = readerEngine.ReadStream(reader);
var csvRecords = fixedWidthRecords.Select(r => new CsvType
{
BranchCode = r.BranchCode,
// ...
}).ToList();
Console.WriteLine(csvRecords.Count()); // output: 2
// write csv data
writerEngine.WriteStream(writer, csvRecords);
Console.WriteLine(sw.ToArray().Count()); // output: 0
File.WriteAllBytes("newfile.csv", sw.ToArray());
}
The above code writes a blank file. ps: I know I can use writerEngine.WriteFile to accomplish the above(which does work btw), but I specifically need a stream in my case. The purpose of writing the file above is only to view the output.
While closing a
TextWriterand/or its underlyingStream(either an via an explicit.Close()or.Dispose()call - or implicitly via ausing(){}block orusing;statement will also flush it, if you intend to read back from aStreamafter writing to it without closing it, then you'll need to flush theTextWriterbecause it has its own buffer, and you may also need to rewind the stream by setting.Positiontoo - and take advantage ofleaveOpen: truetoo.But if you look at your program's application logic, you don't actually need to
Flushanything, just change your code to this:StreamorTextWriter/TextReaderis being used only for input and/or output, you should put the word "input" or "output" (or "in" / "out") in their names to make things easier to follow.