繁体   English   中英

使用C#打开一个txt文件并读取文件上的数字

[英]Open a txt file using C# and read the numbers on the file

如何打开 .txt 文件并将由输入或空格分隔的数字读取到数组列表中?

例子:

现在我想要做的是搜索(为 1 2 9 )并发送到控制台。

我已经尝试了很多代码,但似乎没有任何效果:(

这是我当前的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Padroes
{
class Program
{
    static void Main(string[] args)
    {
        try
        {


            // Open the text file using a stream reader.
            const string FILENAME = @"Example.txt";


                List<List<int>> data = new List<List<int>>();

                string inputLine = "";
                StreamReader reader = new StreamReader(FILENAME);

                while ((inputLine = reader.ReadLine()) != null)
                {
                    inputLine = inputLine.Trim();
                    if (inputLine.Length > 0)
                    {
                        List<int> inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList();

                        data.Add(inputArray);
                    Console.WriteLine(inputLine);
                    }
                }
            }

        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

        Console.ReadKey();
    }
}
}

使用此代码,这是我的输出:

现在我能做些什么来只搜索 (1 2 9) 并只将 1 2 9 发送到控制台?

我相信这可以解决问题..我只是使用了一个StreamReader并循环遍历每一行..我不确定我是否得到了条件的一部分 100% 但如果我这样做应该看起来像这样:

      StreamReader file = new StreamReader(@"test.txt");
      string line= file.ReadLine();
        while(line!=null)
        {
            if (line.Equals("5 8 1 7"))
                MessageBox.Show(line);
               line = file.ReadLine();
        }

祝你好运。

尝试这个

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            List<List<int>> data = new List<List<int>>();

            string inputLine = "";
            StreamReader reader = new StreamReader(FILENAME);

            while((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                if (inputLine.Length > 0)
                {
                    List<int> inputArray = inputLine.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList();

                    data.Add(inputArray);
                }
            }
        }
    }
}
​

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM