1
  1. My app installs SQL Server Express
  2. Have many .mdf and .ldf files on a disk
  3. app copies all the databases and log files to SQL Server data directory
  4. app attempts to attach the databases programmatically.

My code is:

FileInfo mdf = new FileInfo(dbfile);

databasename = mdf.Name.ToLower().Replace(@".mdf", @"");
StringCollection databasefiles = new StringCollection();
databasefiles.Add(mdf.FullName);
databasefiles.Add(mdf.FullName.ToLower().Replace(@".ldf", @"")); 
//this is where I have issue. Obviously I can't assume that the log file name would be the same as mdf file name with ldf extension. Thats when I thought there would be a way to read the header information from mdf file, and that will have ldf information.

Server sqlServer = new Server(textServer.Text);
sqlServer.AttachDatabase(databasename, databasefiles);

How do I pick the correct .ldf file. For eg in c:\temp I have db1.mdf, db2.mdf and db1.ldf, db_1.ldf, db1_log.ldf. How would I know which is the right .ldf file for db1.mdf

1
  • Sorry I wasn't clear, my question is how do I pick the correct .ldf file. For eg in c:\temp I have db1.mdf, db2.mdf and db1.ldf, db_1.ldf, db1_log.ldf. How would I know which is the right .ldf file for db1.mdf. I updated my question also Commented Nov 18, 2011 at 19:44

1 Answer 1

1

No, as far as I know, there's no real "link" between the MDF and LDF file in the files per se. There is a link - in the database metadata inside SQL Server.

My approach would probably be:

  • check if mydatabase.ldf exists -> if yes, use that
  • check if mydatabase_log.ldf exists -> if yes, use that
  • check if mydatabase_1.ldf exists -> if yes, use that

and if you still haven't found your LDF file - you could probably do a search for mydatabase*.ldf in the directory where your MDF is located. That would fail miserably on our test servers - our sysadmins always installed the .MDF/.NDF data files into a SQL2008-DATA and the .LDF log files into a SQL2008-LOG directory - totally separate.

In that case, you would either need to configure your mapping .MDF -> .LDF in e.g. a config file or something, or just pop up a "Find the .LDF file" dialog to the user....

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

3 Comments

I guess this is the only option I have so far. Thanks for the idea, it didn't strike me before.
@gangt: the only other option would be to "fish out" that information from the original server's database metadata and store it in some kind of a "installation config" file or something and read it from there...
Thats not possible, I don't have the original server information. All I got are the database files.

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.