1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

reading from a file and writing to an array

Discussion in 'C#' started by ekbehnke, Sep 12, 2009.

  1. ekbehnke

    ekbehnke New Member

    Joined:
    Sep 12, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    im trying take a file of many random numbers and place it into an array for sorting purposes, but i can't seem to get the array to read the file correctly. here is my code thus far:
    static void Main(string[] args)
    {

    //TextWriter tw = new StreamWriter("project.txt");
    /*Random numGen = new Random();
    //tw.Write("1000 ");
    for (int counter = 0; counter <= 1000; counter++)
    {
    int ranNum = numGen.Next(-500, 500);
    tw.Write(ranNum + " " );

    }*/
    //tw.Close();

    TextReader tr = new StreamReader("project.txt");
    TextWriter Atw = new StreamWriter ("test.txt");

    int[] ranArr = new int[1000];
    for (int x = 0; x < ranArr.Length; x++)
    {

    ranArr[x] = tr.Read();
    Atw.Write(ranArr[x] + " ");

    }


    i've commented out some things as i was trying to trouble shoot with a smaller file, i hope someone here can lend me a hand, thanx in advance, also it has to be an array, not an array list
     
  2. pasanindeewara

    pasanindeewara New Member

    Joined:
    Aug 2, 2009
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    SE
    Location:
    Ice Age
    Check the below.

    System.IO.StreamReader EMPStrReader = new System.IO.StreamReader("C:\\Users\\Pasan Indeewara\\Desktop\\num.txt");

    String kk = EMPStrReader.ReadToEnd();

    string [] splitelements = new string[1];
    splitelements[0] = "\r\n";

    String[] strarr = kk.Split(splitelements, StringSplitOptions.RemoveEmptyEntries);

    int [] MyIntArray = new int [strarr.Length];

    for (int w = 0; w < MyIntArray.Length; w++)
    MyIntArray[w] = Convert.ToInt32(strarr[w]);

    It will solve your problem.

    Regards,
    Pasan Indeewara
     

Share This Page