1

I am trying to read the same file twice.

I have been using a FileUpload to look up the file. I was successful in the first read where I find out how many lines the file have, using the next code in C# ans asp.net:

Stream data_file;
data_file=FileUpload1.PostedFile.InputStream;
string line;
int elements;
StreamReader sr = new StreamReader(data_file);
line = sr.ReadLine();
while (line != null)
{
elements = elements + 1;
line = sr.ReadLine();
}
sr.Close();

With this number I can now create an array of array by setting fist how many elements the array is going to hold. The array this time is going to hold the number from the file something like this:

datafile:

1,1

2,3

arrayL[0][0]=1

arrayL[0][1]=1

arrayL[1][0]=2

arrayL[1][0]=3

so the code to do this is the next:

double [][] dime= new double [elements][];
string[] div;
string line2;
int nn=0;
StreamReader ssr = new StreamReader(data_file);
line2 = ssr.ReadLine();
while (line2 != null)
{
dimen[nn] = new double[2];
for (int m2 = 0; m2 < 2; m2++)
{
div=line2.Split(new Char[] { ' ', ',', '\t' });
dimenc[nn][m2] = Convert.ToDouble(div[m2]);
}
nn=nn+1;
line2 = ssr.ReadLine();
}
ssr.Close();

However, the array says that it is empty but I know if I used the second part of the code in a complete diferrent method/ second button but if it is in the same method it does not work so my question is:

What's wrong? Why the second streamreader is not working?

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
JUAN
  • 523
  • 4
  • 10
  • 27
  • 1
    This is not the respond you are asking for, but instead of using an array[][], could you use a List>? So you can feed your list with your data on the first iteration. This way, you dont need to iterate twice on the same data. A list of list might not be the best structure to use, may be List would fit better. But I think you get the idea. – NLemay Nov 16 '12 at 16:47
  • you kind of right but the problem is that for my final program its not good since what i an tring to do is read the file and send to the array if i used a list and past to the array i will be using more memroy that i need to used, some of my previos programs work as you saing – JUAN Nov 16 '12 at 17:00

1 Answers1

1

Actually @NLemay comment is probably the better solution.

But in the case someone would need to read an uploaded file twice, you would need to cache the file in memory. Either read the stream into a byte[] or a MemoryStream then work your streamreader from that. You'll find that HttpPostedFile.InputStream.CanSeek is false, which is what you're trying to do.

For a byte[]:

HttpPostedFile uFile = uploadFile.PostedFile;

byte[] data = new byte[uFile.ContentLength];
uFile.InputStream.Read(data, 0, uFile.ContentLength);

For a MemoryStream look up a CopyStream method.

Community
  • 1
  • 1
Thymine
  • 8,775
  • 2
  • 35
  • 47