When I tried to read a file when I called DoSomething();(from Something();) in a method, TestProgram_Load()I came across NullReferenceExceptionwith which I am having problems.
This happens when you try to check for a file or even try to read it. However, I can write to the file without problems and refer to the string value even in the debugger.
Here is the problem code:
string fileName = "file.txt";
public void DoSomething()
{
if (File.Exists(fileName))
{
using (StreamReader r = new StreamReader(fileName))
{
}
}
}
And the method that calls it:
public void Something()
{
if (!File.Exists(fileName))
{
using (StreamWriter w = new StreamWriter(fileName))
{
w.Write("Test");
}
}
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 executed in the main functions of the program launch: either in the constructor or in the method TestProgram_Load(): both have the same problem. There should be no threads.
Here are some key details:
- I am trying to read a file,
DoSomething(); File.Exists(fileName)File.Exists(fileName) , .- .
- .
- , .
, , , . ?