views:

132

answers:

7

I have a text file named C:/test.txt:

1 2 3 4
5 6

I want to read every number in this file using StreamReader.

How can I do that?

A: 

I might be wrong but with StreamReader you cannot set delimeter. But you can use String.Split() to set delimeter (it is space in your case?) and extract all numbers into separate array.

Captain Comic
A: 

Something like this:

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());
    }
}
}
Salv0
Erm... Maybe I'm missing something here (it's cold and my brain doesn't like the cold). Why are you deleting the input file, then trying to open it?
ZombieSheep
ahah you'r right xD I was writing fast and intellisense makes the joke :)
Salv0
A: 

Something like this ought to work:

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));
}
Mark Seemann
+1  A: 
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();
  }

}
Anwar Chandra
good answer, but slooow
bniwredyc
i mean solution is slow not the answer (%
bniwredyc
+1  A: 

Something like so might do the trick, if what you want is to read integers from a file and store them in a list.

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
}
Banang
+1  A: 

Solution for big files:

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();
    }
}
bniwredyc
+5  A: 

Do you really need to use a StreamReader to do this?

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

(Obviously if it's impractical to read the entire file in one hit then you'll need to stream it, but if you're able to use File.ReadAllText then that's the way to do it, in my opinion.)

For completeness, here's a 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);
            }
        }
    }
}
LukeH