Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with reading last 2 lines of a file

Status
Not open for further replies.

surovi99

IS-IT--Management
Feb 11, 2005
28
US
Hi,

I am trying the following codes for reading last 2 lines of a file. But I am getting some errors like:
a)The best overloaded method match for
'System.IO.Stream.Read(byte[], int, int)' has some invalid
arguments
b)Argument '2': cannot convert from 'long' to 'int'

byte[] buffer = new byte[1024];
using (Stream s = File.OpenRead(@"C:\Msg.txt"))
{
if (s.Length < buffer.Length)
{
buffer = new byte[s.Length];
}
s.Read(buffer, s.Length - buffer.Length, buffer.Length);
}
Array.Reverse(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0, count = 1; i < buffer.Length; i++)
{
if (buffer == (byte)'\n' && buffer[i + 1] == (byte)'\r') count++;
if (count == 2) break;
sb.Insert(0, buffer);
}

How can I resolve the above errors?

Any help much appreciated.

Thanks.
 
Not looking over the whole code too carefully, I do see that you can correct the error you are getting by explicitly casting the values in the Read Method to ints. I believe the complier won't do it automatically because data can be lost moving to a long to an int, so it is for your benefit.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
a)The best overloaded method match for
'System.IO.Stream.Read(byte[], int, int)' has some invalid

The function takes a byte array and two integers, your code gives it a byte array and two "long" variables. When you receive the length from a stream it is returned as a long.

As Guru said above you need to cast the values to int's, for example:

s.Read(buffer, (int)s.Length - (int)buffer.Length, (int)buffer.Length);

But as Guru also said, there is a reason this is not done by the compiler. If a file is very large then an integer may not be able to contain the length and so converting it to an int would result in a loss of data.

If your not dealing with huge files, this probably wont be much of an issue to you and you can solve the problem by doing as Guru said and as I have shown in the example code above.

I believe this also answers your second question as it relates to the same subject.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top