[英]Reading content from a text file saved to a byte field in SQL Server
I'm missing something in between. 我之间缺少一些东西。 I store the CSV file content in databas, not in a file. 我将CSV文件内容存储在数据库中,而不是文件中。 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);
If we assume that x23.FileData
is a byte[]
, you probably want: 如果我们假设x23.FileData
是byte[]
,则您可能需要:
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. 现在, lines
具有所有单独的行。 Note you could also consume this data in a non-buffered way via IEnumerable<string>
. 请注意,您还可以通过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;
}
}
You are getting that error because x23File
is not a byte[]
. 因为x23File
不是byte[]
,所以x23File
了此错误。 Your second line should actually be 您的第二行实际上应该是
string[] Lines = System.Text.Encoding.UTF8.GetString(x23File.FileContents).Split(new String[]{"\\r\\n"}, StringSplitOptions.None);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.