469,645 Members | 1,646 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,645 developers. It's quick & easy.

Check for empty text file

I am reading the contents of a text file into variables. All works well if the text file does not exist, or it does exist and contains 4 rows of data. But I need to account for rows being empty or null. How can I check this?

Expand|Select|Wrap|Line Numbers
  1. string filename = @"C:\Program Files\Picture Capture\Settings.txt";
  2.         if (File.Exists(filename))
  3.         {
  4.             StreamReader reader = new StreamReader(filename);
  5.             string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
  6.             string[] arrLines = strAllFile.Split(new char[] { '\n' });
  7.             //need to account for an empty file
  8.             this.clienttype = arrLines[0];
  9.             this.servername = arrLines[1];
  10.             this.username = arrLines[2];
  11.             this.password = arrLines[3];
  12.             reader.Close();
  13.  
Oct 9 '09 #1
10 19049
tlhintoq
3,525 Expert 2GB
You might want to look at ReadLine method that already makes the line breaks for you.
I would recommend you read into a temporary array, then qualify each of your lines before assigning them to their final variables. As you have seen you can assume that things are as you expect. Users have an amazing capacity to screw things up.

Expand|Select|Wrap|Line Numbers
  1.         private void Reader()
  2.         {
  3.             string filename = @"C:\Program Files\Picture Capture\Settings.txt";
  4.             if (System.IO.File.Exists(filename))
  5.             {
  6.                 System.IO.StreamReader reader = new System.IO.StreamReader(filename);
  7.                 List<string> Temp = new List<string>();
  8.                 try
  9.                 {
  10.                     while (true)
  11.                     {
  12.                         Temp.Add(reader.ReadLine());
  13.                     }
  14.                 }
  15.                 catch (Exception)
  16.                 {
  17.                     // I hit the end of the file, or some other error
  18.                 }
  19.                 finally
  20.                 {
  21.                     reader.Close();
  22.                 }
  23.  
  24.                 // Qualify that ClientType meets your requirements
  25.                 this.clienttype = Temp[0];
  26.  
  27.                 // Qualify that ServerName is valid
  28.                 this.servername = Temp[1];
  29.  
  30.                 // And so on
  31.             }
  32.         }
  33.  
Oct 9 '09 #2
What is this line...

List<string> Temp = new List<string>();

It is throwing errors.
Oct 9 '09 #3
tlhintoq
3,525 Expert 2GB
add the using statements

using System.Collections;
using System.Collections.Generic;

A List<T> is an advanced type of array with added methods for things like
.RemoveAt(5) to remove the 6th element of the List.
If you use an array you have to handle the moving of all the other elements downward. Adding is more problematic since you have to array.Resize(newsize) the thing.
Oct 9 '09 #4
I added those using statements and I am still getting errors on the List<string>. "The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)".
Expand|Select|Wrap|Line Numbers
  1.     public void GetSettings()
  2.     {
  3.         string filename = @"C:\Program Files\Picture Capture\Settings.txt";
  4.         if (File.Exists(filename))
  5.         {
  6.             System.IO.StreamReader reader = new System.IO.StreamReader(filename);
  7.             List<string> Temp = new List<string>();
  8.             try
  9.             {
  10.                 while (true)
  11.                 {
  12.                     Temp.Add(reader.ReadLine());
  13.                 }
  14.             }
  15.             catch (Exception)
  16.             {
  17.                 // I hit the end of the file, or some other error 
  18.             }
  19.             finally
  20.             {
  21.                 reader.Close();
  22.             }
  23.  
  24.             this.clienttype = Temp[0];
  25.             this.servername = Temp[1];
  26.             this.username = Temp[2];
  27.             this.password = Temp[3];
  28.         }
  29.     }
  30.  
Oct 14 '09 #5
tlhintoq
3,525 Expert 2GB
@klharding
I added those using statements and I am still getting errors on the List<string>. "The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)".
As you can see by the MSDN page for List<T> it *is* part of the System.Collections.Generic namespace.

So it sounds like you haven't put in the using statement where it applies to the List<T>.

You can always type the full namespace to make sure it references the correct namespace.
Change line 7 from
Expand|Select|Wrap|Line Numbers
  1. List<string> Temp = new List<string>();
to
Expand|Select|Wrap|Line Numbers
  1. System.Collections.Generic.List<string> Temp = new System.Collections.Generic.List<string>();
Oct 14 '09 #6
Ok that worked. But now that it is getting to the while(true) statement it is in an infinite loop...it just keeps going through!

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.      while(true)
  4.      {
  5.           Temp.Add(reader.ReadLine());
  6.      }
  7. }
Oct 14 '09 #7
tlhintoq
3,525 Expert 2GB
I would have expected it to throw an error when it could no longer read a line, and throw itself out via the catch portion of the try/catch

I guess it actually pays to read the MSDN for such things.
But you can see there how to easily take care of that.
Sorry I goofed on that one.
Oct 14 '09 #8
Ok, the following seems to work, although I am still getting errors on a blank text file. I would prefer it would just set the varibles to "" rather than error out...
Expand|Select|Wrap|Line Numbers
  1. public class GlobalVariables
  2. {
  3.     private string clienttype;
  4.     private string servername;
  5.     private string username;
  6.     private string password;
  7.     private string filename = @"C:\Program Files\Picture Capture\Settings.txt";
  8.  
  9.     public void GetSettings()
  10.     {
  11.         if (File.Exists(filename))
  12.         {
  13.             int counter = 0;
  14.             string line;
  15.             StreamReader sr = new StreamReader(filename);
  16.             List<string> Temp = new List<string>();
  17.  
  18.             while ((line = sr.ReadLine()) != null)
  19.             {
  20.                 Temp.Add(line);
  21.                 //Console.WriteLine(line);
  22.                 counter++;
  23.             }
  24.  
  25.             sr.Close();
  26.  
  27.  
  28.             clienttype = Temp[0];
  29.             servername = Temp[1];
  30.             username = Temp[2];
  31.             password = Temp[3];
  32.         }
  33.     }
Oct 14 '09 #9
GaryTexmo
1,501 Expert 1GB
I'd be a bit concerned with that code. You're assuming Temp contains 4 elements, which is probably where your errors are coming from with a blank file. I'd highly suggest something along the lines of the following...

Expand|Select|Wrap|Line Numbers
  1. while (...) { ... } // here is where you read your file
  2.  
  3. if (Temp.Length == 0)
  4. {
  5.   // file is empty... or you may have to check each element of temp to see if it's "", but I think the readline won't put anything in here if it's blank
  6. }
  7. else if (Temp.Length == 4) // or perhaps some better comparison
  8. {
  9.   // assign your variables
  10. }
  11. else
  12. {
  13.   // Whatever you want this to be
  14. }
A little error checking goes a long way! Also, personally I'd recommend putting the whole thing in a try/catch block. I like to do this when any kind of file access is involved because the possibility for unforseen error is so high. What I mean by that is, someone could delete your file while the program runs, or someone could have it open for write access. Again though, this is personal opinion... a lot of people don't like try/catch blocks because the involve a certain amount of overhead and indeed, in a more controlled environment I'd say do your error checking yourself, but for something with so many external factors, let the try/catch system handle it for you.
Oct 14 '09 #10
I agree, definitely check the file size with FileInfo.Length and define what you should do if the file is empty, etcetera.
Oct 15 '09 #11

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

19 posts views Thread by wetherbean | last post: by
6 posts views Thread by Poppy | last post: by
1 post views Thread by JenHu | last post: by
7 posts views Thread by elnoire | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.