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 2015ProjectsTest ProgramTest ProgramClassesFileSystemTestClass.cs:line 39 at TestProgram.Program.Main() in Visual Studio 2015ProjectsTest ProgramTest ProgramProgram.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,Object state) at System.Threading.ThreadHelper.ThreadStart() 第39行: if (File.Exists(fileName)) 此代码正在主程序的启动函数中执行:在构造函数或TestProgram_Load()方法中:两者都有相同的问题.根本不应该有任何线程. 以下是一些关键细节: >我尝试读取文件DoSomething(); 我希望这实际上检测存在,当然,打开文件.这里发生了什么? 解决方法
有趣的是,documentation for File.Exists表示:
我最初的倾向是相信在你试图阅读时写作仍在完成,但根据文档,这应该仍然是假的.这听起来像是一个内部.Net错误. 我没有明确的答案,但你可以通过以下方式找到根本原因: >在写入1000ms后放置一个Thread.Sleep 如果这些不起作用,并且您知道字符串第一次工作,则可以尝试完全切换到使用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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |