When attempting to read a file while calling DoSomething();
(from Something();
) in the TestProgram_Load()
method, I encounter a NullReferenceException
, which I'm having trouble making sense of.
This happens when attempting to check if a file exists, or even attempting to read it. However, I am able to write to the file without an issue, and reference the string value, even in the debugger.
Here's the problem code:
// No matter the file name, this fails every time.
string fileName = "file.txt";
public void DoSomething()
{
if (File.Exists(fileName)) // NullReferenceException
{
using (StreamReader r = new StreamReader(fileName)) // NullReferenceException
{
}
}
}
And the method that calls it:
public void Something()
{
// This works fine
if (!File.Exists(fileName))
{
// This works fine
using (StreamWriter w = new StreamWriter(fileName))
{
w.Write("Test");
}
}
// Test to see if there's an issue with this method too...
// This is fine, but whether or not File.Exists(fileName) is used, DoSomething(); has the same problem.
if (File.Exists(fileName))
{
DoSomething();
}
}
Here's the TestProgram_Load method:
private void TestProgram_Load(object sender, EventArgs e)
{
TestClass t = new TestClass();
t.Something();
}
Here's the stack trace:
at TestProgram.TestClass.DoSomething() in Visual Studio 2015\Projects\Test Program\Test Program\Classes\FileSystem\TestClass.cs:line 39
at TestProgram.Program.Main() in Visual Studio 2015\Projects\Test Program\Test Program\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
And Line 39:
if (File.Exists(fileName))
This code is being executed in the main program's startup functions: either in the constructor, or the TestProgram_Load()
method: both are having the same issue. There should not be any threading at all.
Here are some key details:
- I attempt to read the file,
DoSomething();
- The string value exists in the debugger, and can be referenced right before
File.Exists(fileName)
File.Exists(fileName)
works in a different method, but not this one.- The string is not being updated at all.
- The string value is hard-coded.
- There are no additional threads to interfere with this.
I want this to actually detect existence and, of course, open the file. What's going on here?