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?

Samuel Smith
  • 139
  • 1
  • 1
  • 13
  • 2
    You might want to read [this](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp) 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. – ProgrammingLlama Mar 11 '19 at 01:25
  • 1
    Just read it from configuration – Nkosi Mar 11 '19 at 01: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. – Chetan Mar 11 '19 at 01:26
  • 2
    In reference to @Nkosi's excellent sugestion, [this is how to do it](https://stackoverflow.com/questions/50507382/store-retrieve-connectionstring-from-appsettings-json-in-asp-net-core-2-mvc-ap) (since it seems that you're using ASP.NET Core). – ProgrammingLlama Mar 11 '19 at 01: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 – Nkosi Mar 11 '19 at 01:28
  • Closed as duplicate. If the duplicate does not apply to your problem, edit the question with the relevant details and see if it can be reopened and addressed directly. – Nkosi Mar 11 '19 at 01:34

0 Answers0