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? -
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();
-
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. - 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
-
}
-
}
-
What is this line...
List<string> Temp = new List<string>();
It is throwing errors.
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.
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?)". - 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];
-
}
-
}
-
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 - List<string> Temp = new List<string>();
to - System.Collections.Generic.List<string> Temp = new System.Collections.Generic.List<string>();
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! -
try
-
{
-
while(true)
-
{
-
Temp.Add(reader.ReadLine());
-
}
-
}
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.
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... - 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];
-
}
-
}
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... - 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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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
|
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.
|
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:
|
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...
| |
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...
|
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...
|
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")
|
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{
|
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...
|
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...
| |
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...
|
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...
|
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...
|
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...
|
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();...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |