473,394 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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 20839
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

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

Similar topics

19
by: wetherbean | last post by:
Hi group..I am writing a playlist management protocol where I have a file that holds all the playlists and a file that holds all the songs....before a playlist is created I need to check to see if...
2
by: Tarren | last post by:
Hi: I want to check my text file to ensure the last line has only DONE on it, prior to loading the file. How can I do this with a StreamReader object to go to the last line so I can perform...
6
by: Poppy | last post by:
I use the following code to append a line of text to a text file : Dim myFILENAME As String = Server.MapPath("/ABACUS/cvdocs/" & fileName) Dim objStreamWriter As StreamWriter objStreamWriter =...
1
by: JenHu | last post by:
Hi experts, I want to create a new empty text file after I upload a file to the desination. Then I need to read each line from the uploaded file and write the lines which first character <>'6'...
5
by: CCLeasing | last post by:
Hello, I have searched google but can not find a straight forward answer to my problem. Hopefuly someone will be kind enough to offer their expertise. Please forgive if this seems a bit convoluted...
3
by: Gary | last post by:
Hi in a simple application that consists of a couple of user input forms. I'm wondering what the difference is between using a database technology and a plain text file? I've been working on...
8
by: glaskan | last post by:
This code is meant to take an input from the serial port and then save the input from the serial port as the name and as the data to a text file but all i am getting is an empty text file or a text...
7
by: elnoire | last post by:
Greetings! I've just started learning python, so this is probably one of those obvious questions newbies ask. Is there any way in python to check if a text file is blank? What I've tried to...
8
by: jyaseen | last post by:
I used the follwing code to download the text file from my server location. my php file to read the following code name is contacts.php it is downloading the text file but , this text file...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.