Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   reading from a file and writing to an array (http://www.go4expert.com/forums/reading-file-writing-array-t19399/)

ekbehnke 12Sep2009 22:36

reading from a file and writing to an array
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 + " " );


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

pasanindeewara 17Sep2009 09:51

Re: reading from a file and writing to an array
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.

Pasan Indeewara

All times are GMT +5.5. The time now is 08:49.