I have a little spoky problem here. I really cant understand what it is.
I am reading a file that is completely empty. But still the second MessageBox is showing this string:

"22"

I cant wrap my head around why if( line != "" ) is executing and no character is shown inbetween the "22" ?

String^ line = "";
 WebClient^ Client = gcnew WebClient();

 Client->Credentials = gcnew NetworkCredential("username", "password");
 Stream^ strm = Client->OpenRead("file1.txt");
 StreamReader^ sr = gcnew StreamReader(strm);    

 line = sr->ReadLine();
 sr->Close();
 strm->Close();


 if( line == "" )
 {
	 MessageBox::Show("1" + line + "1");
 }
 if( line != "" )
 {
	 MessageBox::Show("2" + line + "2");
 }

Recommended Answers

All 5 Replies

I'm not familiar enough with .NET to know the exact operator(s) you need, but as I understand things, "String^ line" is a pointer to a string, it is not an actual string. Try to de-reference the pointer when you do your comparison.

That's just my 2-cents. Take it how you like.

Thanks, okay, but I am quite shure that this is a correct declaration for a string. Anyway this is the way I always have done it:

String^ line = "";

This happens because StreamReader::ReadLine returns nullptr when the end of stream is reached (which is the case when reading an empty file).

That means that on line 8 of your code line is now nullptr , and not the initial empty string. Since they do not compare equal to each other, the second if statement is entered, and because nullptr does not have a string representation, nothing is printed between the two 2's.

To observe the correct behavior, change the last part to:

if ( String::IsNullOrEmpty( line ) )
{
	MessageBox::Show("1" + line + "1");
}
else
{
	MessageBox::Show("2" + line + "2");
}
commented: Good +4

Like I said, I'm not that familiar with .NET. All I can do is mention some general concepts and see if they spark something for you. AFAIK, that is a correct declaration...

I was actually referring to Lines 13 and 17.

[edit]
Oops, overlapped with a much better answer...

Thank you, now I understand why it didn´t work, so that did solve that problem

Thanks alot for help!

This happens because StreamReader::ReadLine returns nullptr when the end of stream is reached (which is the case when reading an empty file).

That means that on line 8 of your code line is now nullptr , and not the initial empty string. Since they do not compare equal to each other, the second if statement is entered, and because nullptr does not have a string representation, nothing is printed between the two 2's.

To observe the correct behavior, change the last part to:

if ( String::IsNullOrEmpty( line ) )
{
	MessageBox::Show("1" + line + "1");
}
else
{
	MessageBox::Show("2" + line + "2");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.