(C#)阅读一部分线条

时间:2013-04-19 18:12:31

标签: c# text line streamreader

我有一个文本文件,在其中,它看起来像:

xxxx:value

我想读的只是价值, 我试图操纵:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

但是我没有太多运气,任何帮助都会很棒。

3 个答案:

答案 0 :(得分:2)

你需要遍历每一行并拆分每一行......可能应该检查每一行是否为空并且它确实包含一个冒号......但根据你的数据,这可能是不必要的。

using System;
using System.IO;

class Test
{
    public static void Main()
    {
            try
            {
                using (StreamReader sr = new StreamReader("TestFile.txt"))
                {
                    while (!sr.EndOfStream)
                    {
                        String line = sr.ReadLine();
                        if (line != null && line.Contains(":"))
                            Console.WriteLine(line.Split(':')[1]);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
    }
}

答案 1 :(得分:0)

   using System;
    using System.IO;

    class Test
    {
        public static void Main()
        {
            try
            {
                using (StreamReader sr = new StreamReader("TestFile.txt"))
                {
                    String line = sr.ReadToEnd();
                    string[] array = line.Split(':');                    
                    Console.WriteLine(array[1]);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
    }

答案 2 :(得分:0)

尝试使用string.Split()

Console.WriteLine(line.Split(':')[1]);