473,765 Members | 2,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check for empty text file

13 New Member
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 21095
tlhintoq
3,525 Recognized Expert Specialist
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
klharding
13 New Member
What is this line...

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

It is throwing errors.
Oct 9 '09 #3
tlhintoq
3,525 Recognized Expert Specialist
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.
Oct 9 '09 #4
klharding
13 New Member
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 Recognized Expert Specialist
@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.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
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
klharding
13 New Member
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 Recognized Expert Specialist
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
klharding
13 New Member
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 Recognized Expert Top Contributor
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

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

Similar topics

19
32329
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 the playlist file is empty so that I can assign an integer value to a playlist id field if it is the first playlist being written to the file....can anyone help?? Thanks in advance wetherbean
2
34029
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 the string comparison? Thanks
6
6715
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 = File.AppendText(myFILENAME) objStreamWriter.WriteLine(csvline) objStreamWriter.Close() The code works fine but I need to be a ble to delete the entire contents of the file as well and I cant figure it out.
1
4815
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' to the new file. Can someone show me how to do this? First of all, what is the syntax to create a new text file? Thank you. This is the funcation for upload file:
5
2870
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 but this is probabally a reflection of my not clear understanding of the mechanics behind what i'm trying to achieve. Please bear with it I really could do with your help. I have a simple windows form. There are two controls on the form that I...
3
2081
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 this program for a week or so now and its a hobby project. I have never understood how to work with databases in visual studio (although I have strung together a couple of Microsoft access databases in the past, by trial and error.) As I don't...
8
12318
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 file with only "," in it. It would be much appreciated if anyone could help with this problem. Thanks Private Sub Form_Unload(Cancel As Integer) MSComm1.PortOpen = False ' Close the comm port End Sub Private Sub Timer1_Timer() If...
7
22147
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 do so far is: f = file("friends.txt", "w")
8
3373
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 includes the script of contacts.php too $select_group = $_REQUEST; /*echo "file name ". $select_file = $_FILES;*/ if($select_group == 1){ $qry_contacts = "select eml_id from tbl_contacts "; }else{
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10164
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9835
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.