4

I was wondering why can't I use a custom environment variable in an ASP.NET web.config file like so?

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="ConnectionName" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename='%MyProjectsFolder%\WebAppName\App_Data\Database1.mdf';User Instance=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

I checked through Start -> Run that the file path to .mdf file is valid.

When I run my C# code to connect to database I get the following error:

An attempt to attach an auto-named database for file %MyProjectsFolder%\WebAppName\App_Data\Database1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

1
  • what is the alternate solution you used ? Commented Jan 21, 2017 at 1:47

3 Answers 3

6

Environment variables may not be used in a config file.

Sign up to request clarification or add additional context in comments.

1 Comment

Any other way to use relative paths?
1

You can use: DataDirectory like this:

“Data Source = |DataDirectory|\Mydb.sdf”

And you can change where DataDirectory points: "To set the DataDirectory property, call the AppDomain.SetData"

http://social.msdn.microsoft.com/Forums/en/sqlce/thread/dc31ea59-5718-49b6-9f1f-7039da425296

Caveat, I've never tried this.

1 Comment

The thing is, if you need to read the correct directory from some config file to set it, you might was well just modify the connection string in the web.config file.
0

I don't suppose you've tried:

connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename='~/App_Data/Database1.mdf';User Instance=true"

4 Comments

You see the database file is located in a project other than mine.
Have you tried browsing to it and selecting it in the "Data Connections" browser?
I don't want to hardlink to it. The reason for that is because this project might be moved to and from another computer with a different file path.
It's not "hard linked". It's in a text file. It can be edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.