c# – NullReferenceException在调试时读取字符串或正常运行

在调用DoSomething()时尝试读取文件时; (来自Something();)在TestProgram_Load()方法中,我遇到了一个N​​ullReferenceException,我很难理解.

尝试检查文件是否存在,甚至尝试读取时,会发生这种情况.但是,我能够毫无问题地写入文件,并引用字符串值,即使在调试器中也是如此.

这是问题代码:

// 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)使用不同的方法,但不是这个方法.
>字符串根本没有更新.
>字符串值是硬编码的.
>没有其他线程可以干扰这一点.

我希望这实际上检测存在,当然,打开文件.这里发生了什么?

最佳答案 有趣的是,
documentation for File.Exists表示:

The Exists method returns false if any error occurs while trying to
determine if the specified file exists. This can occur in situations
that raise exceptions such as passing a file name with invalid
characters or too many characters, a failing or missing disk, or if
the caller does not have permission to read the file.

我最初的倾向是相信在你试图阅读时写作仍在完成,但根据文档,这应该仍然是假的.这听起来像是一个内部.Net错误.

我没有明确的答案,但你可以通过以下方式找到根本原因:

>在写入1000ms后放置一个Thread.Sleep
>使用FileInfo而不是File(如果File中存在错误
>不要检查File.Exists并查看您的流是否为您提供了更具描述性的错误

如果这些不起作用,并且您知道字符串第一次工作,则可以尝试完全切换到使用FileInfo类.就像是:

var file = new FileInfo(fileName);
if (!file.Exists())
{
    using (var writer = file.CreateText())
    {
        writer.Write("test");
    }
}
using (var writer = file.OpenText())
{
    // do stuff
}

请原谅我的代码,如果它不构建.我没有在此设备上安装visual studio.

点赞