Reputation: 1499
I'm missing something in between. I store the CSV file content in databas, not in a file. The 2nd line below is wrong, I want to read the byte data and assign it to array of lines. So I can loop the results as if I had read directly from a file on disk. Many thanks...
FileContentResult x23File = File(x23.FileData,
"application/text", x23.Filename);
string[] Lines = System.Text.Encoding.UTF8.GetString(x23File);
Upvotes: 0
Views: 573
Reputation: 1062770
If we assume that x23.FileData
is a byte[]
, you probably want:
List<string> lines = new List<string>();
using(var ms = new MemoryStream(x23.FileData))
using(var reader = new StreamReader(ms, Encoding.UTF8))
{
string line;
while((line = reader.ReadLine()) != null)
lines.Add(line);
}
Now lines
has all the separate lines. Note you could also consume this data in a non-buffered way via IEnumerable<string>
. For example:
static IEnumerable<string> ReadLines(byte[] source, Encoding enc = null)
{
using(var ms = new MemoryStream(source))
using(var reader = new StreamReader(ms, enc ?? Encoding.UTF8))
{
string line;
while((line = reader.ReadLine()) != null)
yield return line;
}
}
Upvotes: 3
Reputation: 3290
You are getting that error because x23File
is not a byte[]
. Your second line should actually be
string[] Lines = System.Text.Encoding.UTF8.GetString(x23File.FileContents).Split(new String[]{"\r\n"}, StringSplitOptions.None);
Upvotes: 0