File activation error when dynamically creating .mdf database

2.6k views Asked by At

I have tried creating a new database using a class that inherits DataContext.CreateDatabase() and I have also tried a method from a StackExchange post, but both result in the same exception being thrown with a similar traceback. I have SQL Server 2008 installed, but I have never used it so it's entirely possible I don't have something basic configured.

What I have tried:

https://msdn.microsoft.com/en-us/library/bb399420(v=vs.110).aspx

using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace sandbox
{
    public class MyDVDs : DataContext
    {
        public Table<DVD> DVDs;
        public MyDVDs(string connection) : base(connection) { }
    }

    [Table(Name = "DVDTable")]
    public class DVD
    {
        [Column(IsPrimaryKey = true)]
        public string Title;
        [Column]
        public string Rating;
    }
    class Program
    {
        public static void Main(string[] args)
        {
            MyDVDs db = new MyDVDs("mydvds.mdf");
            db.CreateDatabase();
        }
    }
}

Create .mdf/.sdf database dynamically

public static void CreateSqlDatabase(string filename)
{
    string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
    using (var connection = new System.Data.SqlClient.SqlConnection(
        "Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
    {
        connection.Open();
        using (var command = connection.CreateCommand())
        {
            command.CommandText =
                String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
            command.ExecuteNonQuery();

            command.CommandText =
                String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
            command.ExecuteNonQuery();
        }
    }
}

The exception and trace:

System.Data.SqlClient.SqlException: A file activation error occurred. The physical file name 'testdb.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)

at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)

at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)

at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)

at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

at sandbox.Program.CreateSqlDatabase(String filename)

at sandbox.Program.Main(String[] args)

1

There are 1 answers

1
user3747260 On BEST ANSWER

Apparently the full file path needs to be specified when creating the DataContext object. Simply using "mydvds.mdf" was not sufficient.