[英]MemoryStream to string[]
我從內存中的zip文件(要求不寫入磁盤)中讀取CSV文件的內容到MemoryStream中。 並使用以下代碼來獲取人類可讀的字符串
string result = Encoding.ASCII.GetString(memoryStream.ToArray());
但是,我們希望結果是一個字符串[]來映射CSV文件中的每一行。
有沒有辦法自動處理?
謝謝
首先,不需要在內存流上調用ToArray
。 只需使用StreamReader
,並重復調用ReadLine()
:
memoryStream.Position = 0; // Rewind!
List<string> rows = new List<string>();
// Are you *sure* you want ASCII?
using (var reader = new StreamReader(memoryStream, Encoding.ASCII))
{
string line;
while ((line = reader.ReadLine()) != null)
{
rows.Add(line);
}
}
您可以使用Split
方法按換行符拆分字符串:
string[] result = Encoding.
ASCII.
GetString(memoryStream.ToArray()).
Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
根據您的CSV文件的內容,這可能是一個比你給予信任更難的問題。
假設這是你的csv:
id,data1,data2
1,一些數據,更多數據
2,“這個元素有一個新的界限
就在田野的中間“,如果你逐行閱讀就會產生問題
如果您只是通過reader.ReadLine()逐行閱讀,如果碰巧在中間插入帶有新行的字段(通常在CSV中允許),則不會得到您想要的內容。 你需要更像這樣的東西
List<String> results = new List<string>();
StringBuilder nextRow = new StringBuilder();
bool inQuote = false;
char nextChar;
while(reader.ReadChar(out nextChar)){ // pretend ReadChar reads a char into nextChar and returns false when it hits EOF
if(nextChar == '"'){
inQuote = !inQuote;
} else if(!inQuote && nextChar == '\n'){
results.Add(nextRow.ToString());
nextRow.Length = 0;
} else{ nextString.Append(nextChar); }
}
請注意,這會處理雙引號。 缺少引號將是一個問題,但它們始終位於.csv文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.