在txt文件中搜索并将结果放在文本框中

时间:2014-09-20 15:22:34

标签: c# file

我有一个类似的文本文件:

; "one"
id_number:*=344E6F4D6F7265486178785454332100

; "two"

id_number:*=3536336A775E3825246E773543563437

; "three"

id:_number*=BDBD2EB72D82473DBE09F1B552A8983

并且以同样的方式和我想要在文件中搜索标题(两个),之后它给了我id_number,我想把id_number放在{{1} }

我用过

textbox

但它不起作用

2 个答案:

答案 0 :(得分:1)

    const string f = @"C:\test.txt";

    static void Main(string[] args)
    {

        // 1
        // Declare new List.
        List<string> lines = new List<string>();

        // 2
        // Use using StreamReader for disposing.
        using (StreamReader r = new StreamReader(f))
        {
            // 3
            // Use while != null pattern for loop
            string line;
            while ((line = r.ReadLine()) != null)
            {

                // 4
                // Insert logic here.
                // ...
                // "line" is a line in the file. Add it to our List.

                if (line.Trim() == "")
                    continue;

                lines.Add(line);
            }
        }

        // 5

        string stringValue = "two";
        int correctIndex = -1;
        // Print out all the lines.
        for (int i=0; i<lines.Count; i++)
        {
            if (lines[i].Contains(stringValue))
            {
                correctIndex = i;
            }
        }

        if(correctIndex == -1)
        {
            Console.WriteLine("item is not found");
        }
        else
        {
            //here you will need probably little more cleaning of the string. If the strings are on 1 line you should search for lines[correctIndex]
            Console.WriteLine(lines[correctIndex + 1]);
        }
    }
}
编辑:我没有看到您的编辑,请检查我的解决方案是否对您有所帮助。如果您想继续使用解决方案,请写下评论。

这应该有效。希望这会对你有所帮助。

答案 1 :(得分:0)

string s, result;
bool bl = false;

using (StreamReader sr = new StreamReader("....txt"))
{
    while ((s = sr.ReadLine()) != null)
    {
        if(s.Contains ("two"))
        {
            bl = true;
        }

        if (s.Contains("id_number") && bl == true)
        {
            result = s.Replace("id_number:*=", "");

            textBox1.Text = result;

            break;
        }
    }
}