簡體   English   中英

C#文本文件瀏覽和文件寫入

[英]C# text file browse and file write

我有一個非常大的文本文件(大約35 000多行信息),我想從中提取某些行並將其放在另一個文本文件中。

文本文件如下所示:

    Feature info
    Feature name: 123456
    Version: 1

    Tokens total: 35
    Tokens remaining: 10

我想提取特征名稱和令牌總數。 我想到的是一個帶有兩個按鈕的表單:一個用於瀏覽文件,另一個用於完成對文件部分的整體讀取和寫入,當然是采用相同的逐行格式。

有人對如何做有任何線索嗎? 我已經搜索過,但還沒有真正找到具體的東西,對於文件讀/寫也很新...

編輯

好的,這是我到目前為止所擁有的,並且可以正常工作:

private void button1_Click(object sender, EventArgs e)
    {

        int counter = 0;
        string line;
        string s1 = "Feature name";
        string s2 = "Tokens total";


        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader("d:\\license.txt");
        using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"D:\test.txt")) 
         while ((line = file.ReadLine()) != null)
          {
              if (line.Contains(s1) || line.Contains(s2))
              {
                  file2.WriteLine(line);
                  counter++;
              }
          }

        file.Close();

這是通過一個按鈕完成的。 我想要的是能夠搜索我想要的文件,然后使用另一個按鈕來完成所有寫入過程

您可以使用StreamReaderStreamWriter讀取/寫入文件

要提取文本的特定部分,你可以使用Regex.Matches ,它將返回匹配 ,那么你可以檢索所定義的組Match.Groups

// Search name
Match mu = Regex.Match(line, @"Feature name: (\d+)");

// Get name
if (mu.Groups.Count == 1) Console.Writeline(mu.Groups[0].Value);

編輯的答案:

您可以將讀取的數據存儲在表單類的屬性或私有字段中。 最好使用String或StringBuilder。 單擊第二個按鈕時,檢查是否存儲了數據並將其寫入輸出文件。

private StringBuilder data = new StringBuilder();

private void button2_Click(object sender, EventArgs e)
{
    if(data.Length > 0)
    {
        using(System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"D:\test.txt"))
        {
            file2.Write(data.ToString());
        }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    // Clear the previous store data
    data.Clear();

    // ...

    System.IO.StreamReader file = new System.IO.StreamReader("d:\\license.txt"); 
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains(s1) || line.Contains(s2))
        {
            sb.AppendLine(line);
            counter++;
        }
    }

    file.Close();
}

請添加用於System.IO的using,並使用using塊包圍StreamReader和StreamWriter,這樣您的代碼將更具可讀性,並且您將不會忘記釋放已使用的資源。

暫無
暫無

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

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