4

I want to ignore a line which is either empty , null or just have space or spaces (white spaces).the keyword here is multiple space. I have tried below codes without success

 if (!string.IsNullOrEmpty(line1))

or

if (line2 != "")

and I dont want to trim the file because I want to capture space space abc space space but not space space space space etc thanks

gdoron
  • 147,333
  • 58
  • 291
  • 367
John Ryann
  • 2,283
  • 11
  • 43
  • 60
  • I would like to point out that you can't get null by reading a line of text from the file (you might get null for the LAST line using some reading mechanisms though). – Daniel Mošmondor Feb 13 '12 at 17:56
  • I added the .net-3.0 for the tags list. We can't know what .net version you're using without saying it... – gdoron Feb 13 '12 at 18:01

2 Answers2

9

.NET Framework 4:

string.IsNullOrWhiteSpace(str);

IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

IsNullOrWhiteSpace on MSDN

.NET Framework < 4:

you can use that line or:

if (value != null && value.Trim().Length > 0)
{...}    

Trim on MSDN

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • is it only in .NET 4? I have to use .NET3. any alternative for me? – John Ryann Feb 13 '12 at 17:51
  • @JohnRyann. Yes that line `String.IsNullOrEmpty(value) || value.Trim().Length == 0;` ... =) – gdoron Feb 13 '12 at 17:52
  • This only exists in the .NET 4.0 Framework and future revisions. Its not clear if he can even use this. The simple solution of course is to use the String.Compare function and Compare it to the whitespace characters. An extension method if he isn't using .NET 4.0 would be a valid solution. – Security Hound Feb 13 '12 at 17:53
  • You could also simplify slightly to `value == null || value.Trim().Length == 0` – Blorgbeard Feb 13 '12 at 17:54
  • awesome. this works : if (value != null && value.Trim().Length > 0) – John Ryann Feb 13 '12 at 18:03
  • @JohnRyann. Why won't it... **:-)** I'm glad to hear. – gdoron Feb 13 '12 at 18:04
1

String.IsNullOrWhiteSpace Method Indicates whether a specified string is null, empty, or consists only of white-space characters.
So it can detect if there are only spaces in the string.

Sergey Gavruk
  • 3,538
  • 2
  • 20
  • 31