0

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

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);
        }
    }
}

但是我这样做的运气并不好,任何帮助都会很棒。

4

3 回答 3

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);
            }
    }
}
于 2013-04-19T18:21:05.370 回答
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);
            }
        }
    }
于 2013-04-19T18:16:26.183 回答
0

尝试使用string.Split()

Console.WriteLine(line.Split(':')[1]);
于 2013-04-19T18:16:56.840 回答