0

I have a ConfigureServices method in Startup.cs which configures my sql connection string.

public void ConfigureServices(IServiceCollection services)
    {

        String connpath;

        try
        {
            StreamReader sr = new StreamReader("C:\\configfolder\\config.txt");
            connpath = sr.ReadLine();
            sr.Close();
            Console.WriteLine(connpath);

            var connection = @'"' + connpath + '"';
            services.AddDbContext<DCCLog_Context>
                (options => options.UseSqlServer(connection));

        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("End Finally");
        }

    }

Currently I'm facing issues moving from hard-coded sql connection to a dynamic one, because the tutorial given by MSDN uses var instead of SqlConnection, as shown below.

var connection = @"Server=DESKTOP\SQLEXPRESS;Database=xLogDB;Trusted_Connection=True;MultipleActiveResultSets=True";
        services.AddDbContext<xLog_Context>
            (options => options.UseSqlServer(connection));

How do I make my sql connection a dynamic one, that reads from a text file?

6
  • 2
    You might want to read this about var. In your example var is implicitly string. So the tutorial is using string, and then options.UseSqlServer(connection) is initializing your DbContext with that connection string. Commented Mar 11, 2019 at 1:25
  • 1
    Just read it from configuration Commented Mar 11, 2019 at 1:25
  • 1
    Can you share the tutorial of MSDN which you are following? What issue you are facing with the current code? Also Storing connection string in Web.config is a better idea then storing it in a text file. Commented Mar 11, 2019 at 1:26
  • 2
    In reference to @Nkosi's excellent sugestion, this is how to do it (since it seems that you're using ASP.NET Core). Commented Mar 11, 2019 at 1:27
  • You are getting a lot of suggestions but you will first need to clarify what it is you are actually trying to do and what platform is being used in order to know which applies to your particular issue Commented Mar 11, 2019 at 1:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.