// 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()
var file = new FileInfo(fileName);
if (!file.Exists())
{
using (var writer = file.CreateText())
{
writer.Write("test");
}
}
using (var writer = file.OpenText())
{
// do stuff
}