Frage

Ich habe eine Textdatei namens C:/test.txt:

1 2 3 4
5 6

Ich mag jede Zahl in dieser Datei mit StreamReader lesen.

Wie kann ich das tun?

War es hilfreich?

Lösung

Haben Sie wirklich brauchen eine StreamReader zu verwenden, um dies zu tun?

IEnumerable<int> numbers =
    Regex.Split(File.ReadAllText(@"c:\test.txt"), @"\D+").Select(int.Parse);

(Natürlich, wenn es unpraktisch ist, die gesamte Datei in einer lesen Hit dann müssen Sie es streamen, aber wenn Sie in der Lage File.ReadAllText verwenden dann, dass die Art und Weise, es zu tun, meiner Meinung nach.)

Für Vollständigkeit, hier ist eine Streaming-Version:

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

Andere Tipps

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

}

So etwas wie so könnte den Trick tun, wenn das, was Sie wollen, ist ganze Zahlen aus einer Datei zu lesen und speichern sie in einer Liste an.

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
}

Lösung für große Dateien:

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

Ich könnte falsch sein, aber mit Stream können Sie nicht gesetzt Begrenzer. Aber Sie können verwenden String.Split (), um Set-Trennzeichen (es ist Raum in Ihrem Fall?) Und extrahieren Sie alle Zahlen in separate Array.

So etwas wie dies funktionieren soll:

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

So etwas wie folgt aus:

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());
    }
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top