0

I'd like my program to reference a relative path to the .mdf file so it can run on a new machine without modifying the connection string.

Environment:

  • Microsoft Visual Studio Community 2019, Version 16.11.8
  • Windows Forms

The connection string is pulled from the dbstring class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sharpening_Teeth
{
    public class dbString
    {
        // modifyTemplate pulls in the connection string from this class
        public static string getConnectionString()
        {
            return "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\vamel\\OneDrive\\Desktop\\test\\Sharpening Teeth\\Sharpening Teeth\\templateDB.mdf";
        }

        public static string getReadQuery()
        {
            return "SELECT template_id, template_name, message_content FROM dbo.message_template";
        }
    }
}

I'm just getting back into programming and I'm stuck. Hopefully someone can point me in the right direction here. Thank you.

Threads reviewed

EDIT

I found a solution on reddit. https://www.reddit.com/r/csharp/comments/k0xaqb/local_db_sql_connection_string_without_using_the/

hurk
  • 1
  • 1
  • 1
    AFAIK, Connection strings don't accept relative paths (and if you could "relative to ***what***?" would be the operative question). I'd suggest that you use the technique in your first link. – RBarryYoung Jan 01 '22 at 15:59
  • To re-emphasize: The first link is the answer to your question. – Mark Benningfield Jan 01 '22 at 16:02
  • Why hard code a connection string? Configuration files have existed since version 1.0 – Steve Jan 01 '22 at 16:02
  • @MarkBenningfield Thanks but where would one modifying DataDirectory as executable's path? – hurk Jan 01 '22 at 16:06
  • @hurk, [this answer](https://stackoverflow.com/questions/34336899/how-is-location-of-data-directory-in-connection-strings-resolved) might be helpful. – Dan Guzman Jan 01 '22 at 16:30
  • See also [what's the issue with AttachDbFilename](https://stackoverflow.com/questions/11178720/whats-the-issue-with-attachdbfilename) you really shouldn't use it at all, as it's deprecated, I'm not sure why @DavidBrowne-Microsoft is recommending you should use it. Instead attach your database properly using `CREATE DATABASE ... FOR ATTACH` – Charlieface Jan 01 '22 at 18:43
  • AttachDbFilename is perfectly fine if you're using SQL Server Express LocalDb. The problems are only with the Service-based install of SQL Server Express. If you're using that, just attach your databases. Don't use a user instance or AttachDbFileName. – David Browne - Microsoft Jan 01 '22 at 21:33

0 Answers0