I have 2 text files, test1.txt
and test2.txt
. test2.txt
is actually a duplicate of test1.txt
.
I want to code something that allows a textbox
to read a value from either of the text files so that if one of the text files is empty, it can read from the other text file for the value and vice versa.
I have tested my code by manually emptying the contents of test1.txt
first, then emptying the contents of test2.txt
which works perfectly as there is always a value appearing on the textbox
. However, when both text files contain contents at the same time, NullReferenceException
is thrown whenever I try to execute it.
Don't mind if I ask because I probably sound stupid, but is it because neither of the files is empty, that's why this exception is thrown? I have read this post about NullReferenceException
, but I don't understand which category my error falls under.
This is a sample of the text files:
^ Michael Johnson^ ^ michaelj^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ michaeljohnson@example.com^ ^ 123456^ ^ ^ 123456^ ^ ^ ^ ^ ^ ^
This is my code:
using System.IO;
Log = @"C:\logs\submission\test1.txt";
Log2 = @"C:\logs\submission\test2.txt";
if (!File.Exists(Log))
{
File.Create(Log).Dispose();
}
if (!File.Exists(Log2))
{
File.Create(Log2).Dispose();
}
FileStream fs1 = new FileStream(Log, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
FileStream fs2 = new FileStream(Log2, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
var sr1 = new StreamReader(fs1);
var sr2 = new StreamReader(fs2);
while (!sr1.EndOfStream || !sr2.EndOfStream)
{
if (new FileInfo(Log).Length != 0)
{
var line1 = sr1.ReadLine();
var values1 = line1.Split('^');
if (values1[3].ToString().Trim() == User.Identity.Name.)
{
number = values1[18].ToString().Trim();
}
if (!(values1[3].ToString().Trim().Contains(User.Identity.Name)))
{
unregisteredUser = User.Identity.Name;
}
}
else
{
if (new FileInfo(Log2).Length != 0)
{
var line2 = sr2.ReadLine();
var values2 = line2.Split('^');
if (values2[3].ToString().Trim() == User.Identity.Name)
{
number = values2[18].ToString().Trim();
}
if (!(values2[3].ToString().Trim().Contains(User.Identity.Name)))
{
unregisteredUser = User.Identity.Name;
}
}
}
}
sr1.Close();
sr2.Close();
fs1.Close();
fs2.Close();
This is the exact location where the exception is thrown:
var values1 = line1.Split('^');