C# 从文本文件读取数字并分隔空白

C# 从文本文件读取数字并分隔空白,c#,arrays,file,integer,C#,Arrays,File,Integer,我有一个外部文本文件,里面有数字。像4 54 12 32被空格隔开。 我希望能够阅读所有数字并将其添加到列表中 static void Main(string[] args) { List<int> numbers; numbers = new List<int>(); StreamReader file = new StreamReader("C:\\text.txt");

我有一个外部文本文件,里面有数字。像4 54 12 32被空格隔开。 我希望能够阅读所有数字并将其添加到列表中

static void Main(string[] args)
        {
            List<int> numbers;
            numbers = new List<int>();

            StreamReader file = new StreamReader("C:\\text.txt");

            while (!file.EndOfStream)
            {
                string line = file.ReadLine();
                Console.Write(line + " ");
            }
        }
static void Main(字符串[]args)
{
清单编号;
数字=新列表();
StreamReader文件=新的StreamReader(“C:\\text.txt”);
而(!file.EndOfStream)
{
字符串行=file.ReadLine();
控制台。写入(行+“”);
}
}

ReadLine读取整行,因此我无法将单个数字分离并将其转换为整数,我尝试读取每个数字的字符代码,而不是数字本身。

字符串对象()的拆分方法就是您要寻找的。

尝试按空格拆分行

string [] numbers = file.ReadLine().Split(new char[]{' '},
                                       StringSplitOptions.RemoveEmptyEntries);

这个方法应该对你有帮助

    public static IEnumerable<int> ReadInts(string path)
    {
        var txt = File.ReadAllText(path);
        return Regex.Split(txt, @"\s+").Select(x => int.Parse(x));
    }
公共静态IEnumerable读入(字符串路径)
{
var txt=File.ReadAllText(路径);
返回Regex.Split(txt,@“\s+”)。选择(x=>int.Parse(x));
}

您可以使用
文件。ReadAllText
方法:

var numbers = File.ReadAllText("C:\\text.txt")
             .Split()
             .Where(x => x.All(char.IsDigit))
             .Select(int.Parse)
             .ToList();