PadRight generating error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi Al

Hopefully this is will be quite simple to answer !!! The following code produces the error "Object reference not set to an instance of an object

Dim objStream As StreamReader = New StreamReader(strFileName
Dim objStringBuilder As StringBuilder = New StringBuilde
Dim strLine As Strin

D
strLine = objStream.ReadLine.PadRight(10,Chr(32)
objStringBuilder.Append(strLine & ChrW(10)
Loop Until (strLine Is Nothing

objStream.Close(

It is probaly something majorly obvious but I cant see it for the life of me

TI

Adrian
 
AdrianFriend said:
Hopefully this is will be quite simple to answer !!! The following
code produces the error "Object reference not set to an instance of
an object.

Dim objStream As StreamReader = New StreamReader(strFileName)
Dim objStringBuilder As StringBuilder = New StringBuilder
Dim strLine As String

Do
strLine = objStream.ReadLine.PadRight(10,Chr(32))
objStringBuilder.Append(strLine & ChrW(10))
Loop Until (strLine Is Nothing)

objStream.Close()

It is probaly something majorly obvious but I cant see it for the life of me.

ReadLine can return a null reference (Nothing in VB) - and you're
trying to dereference that and pad it.
 
Jo

Thanks alot just the pointer I needed. Used the following code instead

Do While objStream.Peek >=
strLine = objStream.ReadLin
strLine.PadRight(1000 - strLine.Length, Chr(32)
objStringBuilder.Append(strLine & ChrW(10)
Loo

Works like a dream. Thanks again

Adrian
 
AdrianFriend said:
Thanks alot just the pointer I needed. Used the following code instead.

Do While objStream.Peek >= 0
strLine = objStream.ReadLine
strLine.PadRight(1000 - strLine.Length, Chr(32))
objStringBuilder.Append(strLine & ChrW(10))
Loop

Works like a dream. Thanks again.

I wouldn't personally use Peek like that.

I'd use ReadLine, test for it being Nothing, and then pad.

However, that's just me - and perhaps C# lends itself to that idiom
more easily. For instance, I'd write:

string line;
while ( (line=objStream.ReadLine()) != null)
{
line = line.PadRight(1000);
...
}

Note that your use of PadRight looks wrong to me - the parameter you
specify is the *total* length you want, not the number of spaces you
want. (The second parameter isn't required either, as the version with
only one parameter gives a space.)

Maybe you've got a different requirement, however - just thought I'd
point it out.
 
Hi Jon

Thanks for your advice. I have changed the code to test for Nothing
instead. Also thanks for pointing the .PadRight syntax error.

All done and dusted now !!

Adrian
 
Back
Top