Creating a database with filestream using (C#) SMO in DotNet 3.5.

The following code will help you to do the creating database with filestream.

Here am using the SMO from Visual Studio Dot Net 3.5. Smo object is very useful to do the sqlserver manipulations from code end. However we could create a db with filestream. Just go thru the following code and use it.

using Microsoft.SqlServer.Management.Smo;

string dbName = "DBName";
string dbServerMachineName = "MachineName";

string mdfFile = mdfDirectory+@"\" + dbName + ".mdf";
string ldfFile = ldfDirectory + @"\" + dbName + "_log.ldf";
string FilesDir = FilesDirectory +@"\" + dbName;

Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(dbServerMachineName);

Database database = new Database(server, dbName);
//Adding Primary FileGroup
database.FileGroups.Add(new FileGroup(database, "PRIMARY"));
//Adding FileStream FileGroup
database.FileGroups.Add(new FileGroup(database, "FileStreamTest", true));
//Adding Files for Primary FileGroup
DataFile dtPrimary = new DataFile(database.FileGroups["PRIMARY"], "PriValue", mdfFile);
dtPrimary.Size = 77.0 * 1024.0;
dtPrimary.GrowthType = FileGrowthType.KB;
dtPrimary.Growth = 1.0 * 1024.0;
database.FileGroups["PRIMARY"].Files.Add(dtPrimary);
//Adding Files for FileStream FileGroup
database.FileGroups["FileStreamTest "].Files.Add(new DataFile(database.FileGroups["FileStreamTest "], " FileStreamTest Values", FilesDir));
//Adding LogFile
LogFile logFile = new LogFile(database, "PriValue_log", ldfFile);
logFile.Size = 7.0 * 1024.0;
logFile.GrowthType = FileGrowthType.Percent;
logFile.Growth = 10.0;
database.LogFiles.Add(logFile);
//Create database.
database.Create();
database.Refresh();

...S.VinothkumaR.

2 comments:

Benjol said...

Nice, this worked great!

Unknown said...

Works Great. Thanks!