簡體   English   中英

如何讀取文本文件然后只顯示換行符之間的文本

[英]How can I read a text file then only display the text that is between line breaks

我正在嘗試讀取一個文本文件,但隨后只顯示兩個換行符之間的文本。 所以例如如果我有這個

 <== Line Break ==> (1)
 This is my text
 <== Line Break ==> (2)
 Some Text
 Some Text
 Some Text
 Some Text
 <== Line Break ==> (3)
 Result
 <== Line Break ==> (4)
 Some other text not needing to show

因此,正如您在上面看到的,我只想顯示“換行符”1 和 4 之間的文本我現在擁有的是:

 string file = "My Text File.txt";
        string[] str = null;
        if (File.Exists(Server.MapPath(file)))
        {
            str = File.ReadAllLines(Server.MapPath(file));
        }
        foreach (string s in str)
        {
            if (s.Contains("This is my text"))
            {
                btnText.Text = s.Replace(s, "Heading 1");
                btnText.OnClientClick = ReadAdvertisingTest();
            }

            else if (s.Contains("This is my failed text"))
            {
                lblError.Text = lblError.Text + "\n" + s.Replace(s, "Heading 2");
            }
        }

 private string ReadAdvertisingTest()
  {
    <== This is where I need to display the text I want to have
  }

上面的代碼通過查找文本然后在Button中顯示來很好地工作,但我不確定如何讓第二部分工作。

編輯所以 output 應該是:

This is my text
 <== Line Break ==> (2) 
 Some Text
 Some Text
 Some Text
 Some Text
 <== Line Break ==> (3)
 Result

所以基本上保留換行符 2 和 3(如果可能的話)

任何建議都會有所幫助

謝謝

    StreamReader sr = new StreamReader(sfile);
    
    while (sr.Peek() != -1)
        {
          
    string strwithoutSplitData = sr.ReadLine().Trim();
      if(strwithoutSplitData.Contains("<Header>") || strwithoutSplitData.Contains("<Footer>"))
    {
    
    if (strwithoutSplitData.Contains("<Footer>"))
    {
    sr.close();
    break;
    }
    }
    else
    {
    //do something
    }
 }

好的,這有點難看,但它會起作用:

string fPath = @"c:\Test5\mytext.txt";
string strBuf = File.ReadAllText(fPath);
TextBox1.Text = strBuf;

List<string> MyList = strBuf.Split(new[] { System.Environment.NewLine }, StringSplitOptions.None).ToList();

MyList.RemoveAt(0);
if (MyList.Count > 2)
   MyList.RemoveRange(3, MyList.Count - 3);
 
string strResult = string.Join(System.Environment.NewLine,MyList);
TextBox2.Text = strResult;

所以我讀了文本文件,把它放在一個文本框中,然后第二個文本框顯示了結果:

在此處輸入圖像描述

事實上,這暗示了很多:

skip first line
grab all text to next line
include the next line

因此,代替 split() function,我們可能只集中拆分的結果並獲取 3 個值來代替“連接”,但無論如何以上應該足夠了。

暫無
暫無

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

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