首页 新闻 赞助 找找看

C# 如何遍历txt文件里的内容

0
悬赏园豆:15 [已解决问题] 解决于 2012-05-02 10:43

txt文件的内容格式如下:

a

b

c

d

------------------------------------请问怎样遍历把a、b、c、d取出来

C#
Philomena的主页 Philomena | 初学一级 | 园豆:154
提问于:2012-04-26 09:32
< >
分享
最佳答案
1
 // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
 try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

上面的都可以。

收获园豆:15
悟行 | 专家六级 |园豆:12559 | 2012-04-26 09:35
其他回答(1)
0

假如是配置文件 还是用xml 把

王大湿 | 园豆:457 (菜鸟二级) | 2012-04-26 09:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册