如何在文本框中显示文本文件中的特定文本行?

时间:2016-09-08 01:10:37

标签: c#

我创建了一个可以打开文件对话框的应用程序,你可以打开一个文件,然后在文本框中显示它的内容。但是,文件中有三个我真正需要的文本块。我需要能够“解析”只显示这些文本块。我用过readalllines。但是,不确定如何通过For each循环进行排序。任何帮助将不胜感激:

我的代码

private void button1_Click(object sender, EventArgs e)
{
    Stream myStream;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    //Setting initial directory to the automated repository
    openFileDialog1.InitialDirectory = "\\\\10.2.XXX.XX\\Repository\\AutomatedVersionRepository\\JMN Web Application\\";

    // Set filter options and filter index.
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|Config files (*.config*)|*.config*";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.Multiselect = true;
    openFileDialog1.RestoreDirectory = true;

    // Call the ShowDialog method to show the dialog box.
    //bool? userClickedOK = openFileDialog1.ShowDialog() ==DialogResult.OK;
    if (openFileDialog1.ShowDialog() ==System.Windows.Forms.DialogResult.OK)
    {
       if ((myStream = openFileDialog1.OpenFile()) !=null)
       {
           string strfilename = openFileDialog1.FileName;
           string []filetext = File.ReadAllLines(strfilename);
           foreach (string line in File.ReadLines(strfilename))
           {
              //process the line
           }
           //richTextBox1.Text = filetext;
       }

文本块示例:

 <!---Interface URLS and settings-->
<add key="IUFUploadPath" value="" />
<add key="JSDskAPIURL" value="http://api.documentation.com/16_4" />
<add key="PvAPIURL" value="http://devapi.documentation.com/16_4" />
<add key="FirstDataWebServiceURL" value="https://dev.SpectrumRetailNet.Com/PPSAPI" />
<add key="ReportServerUrl" value="https://reports64.documentation.com/9_2_0/FrameHost.aspx" />
<add key="HelpassAdminUrl" value="http://Helpppass.documentation.com/app/AdminConsole.aspx" />
<add key="XAIMAPIURL" value="//devquippe.documentation.com/ws.aspx" />

1 个答案:

答案 0 :(得分:0)

这是我将使用的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            Dictionary<string, string> settingsDict = new Dictionary<string, string>();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            XmlReader reader = XmlReader.Create(FILENAME, settings);
            while (!reader.EOF)
            {
                if (reader.Name != "add")
                {
                    reader.ReadToFollowing("add");
                }
                if (!reader.EOF)
                {
                    XElement add = (XElement)XElement.ReadFrom(reader);
                    settingsDict.Add((string)add.Attribute("key"), (string)add.Attribute("value"));
                }
            }
        }
    }
}