我有一个名为C:/test.txt
的文本文件:
1 2 3 4 5 6
我想使用StreamReader
读取此文件中的每个数字。
我该怎么做?
答案 0 :(得分:5)
您真的需要使用StreamReader
来执行此操作吗?
IEnumerable<int> numbers =
Regex.Split(File.ReadAllText(@"c:\test.txt"), @"\D+").Select(int.Parse);
(显然,如果在一次点击中阅读整个文件是不切实际的,那么你需要对它进行流式处理,但如果你能够使用File.ReadAllText
,那么我认为这就是你的方法。 )
为了完整性,这是一个流媒体版本:
public IEnumerable<int> GetNumbers(string fileName)
{
using (StreamReader sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
foreach (string item in Regex.Split(line, @"\D+"))
{
yield return int.Parse(item);
}
}
}
}
答案 1 :(得分:1)
using (StreamReader reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
Regex r = new Regex("[0-9]");
Match m = r.Match(contents );
while (m.Success)
{
int number = Convert.ToInt32(match.Value);
// do something with the number
m = m.NextMatch();
}
}
答案 2 :(得分:1)
try
{
StreamReader sr = new StreamReader("C:/test.txt"))
List<int> theIntegers = new List<int>();
while (sr.Peek() >= 0)
theIntegers.Add(sr.Read());
sr.Close();
}
catch (Exception e)
{
//Do something clever to deal with the exception here
}
答案 3 :(得分:1)
大文件解决方案:
class Program
{
const int ReadBufferSize = 4096;
static void Main(string[] args)
{
var result = new List<int>();
using (var reader = new StreamReader(@"c:\test.txt"))
{
var readBuffer = new char[ReadBufferSize];
var buffer = new StringBuilder();
while ((reader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
foreach (char c in readBuffer)
{
if (!char.IsDigit(c))
{
// we found non digit character
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
buffer.Remove(0, buffer.Length);
}
else
{
buffer.Append(c);
}
}
}
// check buffer
if (buffer.Length > 0)
{
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
}
}
result.ForEach(Console.WriteLine);
Console.ReadKey();
}
}
答案 4 :(得分:0)
我可能错了,但是使用StreamReader你不能设置分隔符。 但您可以使用String.Split()来设置分隔符(在您的情况下它是空格?)并将所有数字提取到单独的数组中。
答案 5 :(得分:0)
这样的事情:
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"C:\Test.txt";
try
{
if( File.Exists( path ) )
{
using( StreamReader sr = new StreamReader( path ) )
{
while( sr.Peek() >= 0 )
{
char c = ( char )sr.Read();
if( Char.IsNumber( c ) )
Console.Write( c );
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
答案 6 :(得分:0)
这样的事情应该有效:
using (var sr = new StreamReader("C:/test.txt"))
{
var s = sr.ReadToEnd();
var numbers = (from x in s.Split('\n')
from y in x.Split(' ')
select int.Parse(y));
}