<分区>
在 TestProgram_Load()
方法中调用 DoSomething();
(来自 Something();
)时尝试读取文件时,我遇到了 NullReferenceException
,我无法理解它。
当试图检查文件是否存在,甚至试图读取它时,就会发生这种情况。但是,即使在调试器中,我也可以毫无问题地写入文件,和引用字符串值。
问题代码如下:
// 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
{
}
}
}
以及调用它的方法:
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();
}
}
这是 TestProgram_Load 方法:
private void TestProgram_Load(object sender, EventArgs e)
{
TestClass t = new TestClass();
t.Something();
}
这是堆栈跟踪:
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()
第 39 行:
if (File.Exists(fileName))
此代码在主程序的启动函数中执行:在构造函数或 TestProgram_Load()
方法中执行:两者都有相同的问题。根本不应该有任何线程。
以下是一些关键细节:
- 我尝试读取文件
DoSomething();
- 字符串值存在于调试器中,可以在
File.Exists(fileName)
之前引用 File.Exists(fileName)
以不同的方法工作,但不是这个。- 字符串根本没有更新。
- 字符串值是硬编码的。
- 没有其他线程会干扰它。
我希望它能实际检测到文件的存在,当然,还能打开文件。这是怎么回事?