Steve2056726
Steve2056726

Reputation: 467

StreamReader Null Reference Exception

Im trying to read SQL statement from .SQL files in a resource folder, I have 2 .SQL files right now and it reads one correctly and the other returns a NullRefrenceException

Here is my calling of the sql files:

 string sqlFailRecordNoMatch = EmbeddedResource.GetString("Resources.SQLScripts.RecordNumberFailQuery.sql");

Here is the GetString method:

public static string GetString(System.Reflection.Assembly assembly, string name)
{
    System.IO.StreamReader sr = EmbeddedResource.GetStream(assembly, name);
    string data = sr.ReadToEnd();
    sr.Close();
    return data;
}

Upvotes: 1

Views: 876

Answers (2)

Oliver
Oliver

Reputation: 45101

It would be much easier if you simply use the resource editor from Visual Studio:

  • Within your project create a new folder (maybe called Queries)
  • Right click this folder and select Add - New Item
  • In the dialog just select Textfile and give it the name about what this query will do
    • Make sure you replace the file extension from .txt to .sql
  • Just put your statement right into this file
  • In the Resource Editor add this file as a resource (normally located in your project under the properties folder or simply also create it by Add - New Item - Resources File)
  • Now you can access this sql statement within your code just by using Properties.Resources.MySqlStatement

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

The only reason you would get a NullReferenceException on one vs. the other is:

  1. The one that's failing isn't set as an Embedded Resource. You can check that by clicking on the file in the Solution Explorer and hitting F4.
  2. You're using the wrong fully qualified path.

I suspect it's #1.

Upvotes: 3

Related Questions