Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to read sql server mdf header for log file information programmatically in c#
    primarykey
    data
    text
    <p>I need to attach databases programmatically but the log file naming conventions don't appear to be same. </p> <p>For example:<br> <code>database1.mdf</code> has <code>database1.ldf</code>, <code>database2.mdf</code> has <code>database2_log.ldf</code> and so on...</p> <p>So, my guess was that the information about the log file would be in the header data of the mdf file, but I'm not sure how to read it.</p> <p>I did a google search and got this code, but it's to read the version information.</p> <pre><code>using (FileStream fs = File.OpenRead(@"C:\database.mdf")) { using (BinaryReader br = new BinaryReader(fs)) { // Skip pages 0-8 (8 KB each) of the .mdf file, // plus the 96 byte header of page 9 and the // first 4 bytes of the body of page 9, // then read the next 2 bytes int position = 9 * 8192 + 96 + 4; br.ReadBytes(position); byte[] buffer = br.ReadBytes(2); dbiVersion = buffer[0] + 256 * buffer[1]; } } </code></pre> <p>======================================================</p> <p>question updated:</p> <ol> <li>My app installs sql express</li> <li>Have many .mdf and .ldf files on a disk</li> <li>app copies all the databases and log files to sql data directory</li> <li>app attempts to attach the databases programmatically.</li> </ol> <p>FileInfo mdf = new FileInfo(dbfile);</p> <pre><code>databasename = mdf.Name.ToLower().Replace(@".mdf", @""); StringCollection databasefiles = new StringCollection(); databasefiles.Add(mdf.FullName); databasefiles.Add(mdf.FullName.ToLower().Replace(@".ldf", @"")); </code></pre> <p>//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.</p> <pre><code>Server sqlServer = new Server(textServer.Text); sqlServer.AttachDatabase(databasename, databasefiles); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload