簡體   English   中英

在文件的兩個帶標簽的行之間獲取所有內容以便可以反序列化的最佳方法是什么?

[英]What's the best way to get all the content in between two tagged lines of a file so that you can deserialize it?

我一直注意到以下代碼段不能很好地用於大型文件(我認為追加到paneContent字符串很慢):

            string paneContent = String.Empty;
            bool lineFound = false;
            foreach (string line in File.ReadAllLines(path))
            {
                if (line.Contains(tag))
                {
                    lineFound = !lineFound;
                }
                else
                {
                    if (lineFound)
                    {
                        paneContent += line;
                    }
                }
            }
            using (TextReader reader = new StringReader(paneContent))
            {
                data = (PaneData)(serializer.Deserialize(reader));
            }

加快這一切的最好方法是什么? 我有一個看起來像這樣的文件(所以我想在兩個不同的標簽之間獲取所有內容,然后反序列化所有內容):

A line with some tag 
A line with content I want to get into a single stream or string
A line with content I want to get into a single stream or string
A line with content I want to get into a single stream or string
A line with content I want to get into a single stream or string
A line with content I want to get into a single stream or string
A line with some tag

注意:這些標記不是XML標記。

您可以使用StringBuilder而不是字符串,這就是StringBuilder的目的。 下面是一些示例代碼:

var paneContent = new StringBuilder();
bool lineFound = false;
foreach (string line in File.ReadLines(path))
{
    if (line.Contains(tag))
    {
        lineFound = !lineFound;
    }
    else
    {
        if (lineFound)
        {
            paneContent.Append(line);
        }
    }
}
using (TextReader reader = new StringReader(paneContent.ToString()))
{
    data = (PaneData)(serializer.Deserialize(reader));
}

就像在這個答案中提到的那樣,當您在循環中串聯時,StringBuilder優先於字符串,在這種情況下就是這樣。

這是一個如何在正則表達式中使用組並隨后檢索其內容的示例。

您想要的是一個與標簽匹配的正則表達式,將其標記為組,然后如示例中那樣檢索組的數據

使用StringBuilder生成數據字符串( paneContent )。 因為連接字符串會導致新的內存分配,所以速度要快得多。 StringBuilder預先分配內存(如果您期望大型數據字符串,則可以自定義初始分配)。

逐行讀取輸入文件是一個好主意,因此,如果您希望文件包含多行文本,則可以避免將整個文件加載到內存中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM