Check for empty text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • klharding
    New Member
    • Oct 2009
    • 13

    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?

    Code:
    string filename = @"C:\Program Files\Picture Capture\Settings.txt";
            if (File.Exists(filename))
            {
                StreamReader reader = new StreamReader(filename);
                string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
                string[] arrLines = strAllFile.Split(new char[] { '\n' });
                //need to account for an empty file
                this.clienttype = arrLines[0];
                this.servername = arrLines[1];
                this.username = arrLines[2];
                this.password = arrLines[3];
                reader.Close();
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    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.

    Code:
            private void Reader()
            {
                string filename = @"C:\Program Files\Picture Capture\Settings.txt";
                if (System.IO.File.Exists(filename))
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(filename);
                    List<string> Temp = new List<string>();
                    try
                    {
                        while (true)
                        {
                            Temp.Add(reader.ReadLine());
                        }
                    }
                    catch (Exception)
                    {
                        // I hit the end of the file, or some other error
                    }
                    finally
                    {
                        reader.Close();
                    }
    
                    // Qualify that ClientType meets your requirements
                    this.clienttype = Temp[0];
    
                    // Qualify that ServerName is valid
                    this.servername = Temp[1];
    
                    // And so on
                }
            }

    Comment

    • klharding
      New Member
      • Oct 2009
      • 13

      #3
      What is this line...

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

      It is throwing errors.

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        add the using statements

        using System.Collecti ons;
        using System.Collecti ons.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(ne wsize) the thing.

        Comment

        • klharding
          New Member
          • Oct 2009
          • 13

          #5
          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?)".
          Code:
              public void GetSettings()
              {
                  string filename = @"C:\Program Files\Picture Capture\Settings.txt";
                  if (File.Exists(filename))
                  {
                      System.IO.StreamReader reader = new System.IO.StreamReader(filename);
                      List<string> Temp = new List<string>();
                      try
                      {
                          while (true)
                          {
                              Temp.Add(reader.ReadLine());
                          }
                      }
                      catch (Exception)
                      {
                          // I hit the end of the file, or some other error 
                      }
                      finally
                      {
                          reader.Close();
                      }
          
                      this.clienttype = Temp[0];
                      this.servername = Temp[1];
                      this.username = Temp[2];
                      this.password = Temp[3];
                  }
              }

          Comment

          • tlhintoq
            Recognized Expert Specialist
            • Mar 2008
            • 3532

            #6
            Originally posted by klharding
            What is this line...

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

            It is throwing errors.
            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.Collecti ons.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
            Code:
            List<string> Temp = new List<string>();
            to
            Code:
            System.Collections.Generic.List<string> Temp = new System.Collections.Generic.List<string>();

            Comment

            • klharding
              New Member
              • Oct 2009
              • 13

              #7
              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!

              Code:
              try
              {
                   while(true)
                   {
                        Temp.Add(reader.ReadLine());
                   }
              }

              Comment

              • tlhintoq
                Recognized Expert Specialist
                • Mar 2008
                • 3532

                #8
                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.

                Comment

                • klharding
                  New Member
                  • Oct 2009
                  • 13

                  #9
                  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...
                  Code:
                  public class GlobalVariables
                  {
                      private string clienttype;
                      private string servername;
                      private string username;
                      private string password;
                      private string filename = @"C:\Program Files\Picture Capture\Settings.txt";
                   
                      public void GetSettings()
                      {
                          if (File.Exists(filename))
                          {
                              int counter = 0;
                              string line;
                              StreamReader sr = new StreamReader(filename);
                              List<string> Temp = new List<string>();
                  
                              while ((line = sr.ReadLine()) != null)
                              {
                                  Temp.Add(line);
                                  //Console.WriteLine(line);
                                  counter++;
                              }
                  
                              sr.Close();
                  
                              
                              clienttype = Temp[0];
                              servername = Temp[1];
                              username = Temp[2];
                              password = Temp[3];
                          }
                      }

                  Comment

                  • GaryTexmo
                    Recognized Expert Top Contributor
                    • Jul 2009
                    • 1501

                    #10
                    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...

                    Code:
                    while (...) { ... } // here is where you read your file
                    
                    if (Temp.Length == 0)
                    {
                      // 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
                    }
                    else if (Temp.Length == 4) // or perhaps some better comparison
                    {
                      // assign your variables
                    }
                    else
                    {
                      // Whatever you want this to be
                    }
                    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.

                    Comment

                    • stoogots2
                      New Member
                      • Sep 2007
                      • 77

                      #11
                      I agree, definitely check the file size with FileInfo.Length and define what you should do if the file is empty, etcetera.

                      Comment

                      Working...