关于FileTable是什么,请猛击如下链接:http://technet.microsoft.com/zh-cn/library/ff929144(v=SQL.110).aspx;如您已知道,请跳过。

关于如何启用FileTable功能,请猛击如下链接:http://technet.microsoft.com/zh-cn/library/gg509097.aspx

关于如何创建、修改和删除FileTable,请猛击如下链接:http://technet.microsoft.com/zh-cn/library/gg509088.aspx

欲了解更多FileTable特性及支持,请点击以上链接页面页底的相关任务部分(如图):

SQL2012之FileTable与C#的联合应用-LMLPHP

在上面的截图中用红色框框圈出的部分,将是本文的重点部分。在新建FileTable后,右击并选择“浏览FileTable目录”,如下图:

SQL2012之FileTable与C#的联合应用-LMLPHPSQL2012之FileTable与C#的联合应用-LMLPHP

没错,也许您已想到,这就是所谓的FileTable支持Windows I/O API操作,这样我们就可以利用System.IO命名空间下的FileInfo类中的Move、Copyto等函数实现利用FileTable上传文件的功能。下面我们将实现如何在C#程序中实现这点:

1.首先要获取到FileTable表的RootPath(也就是上图中圈出的网络路径),就这一点我们可以T-SQL中的函数FileTableRootPath(),比如说我建的FileTable名为MyFirstFileTable,那么T-SQL如下便可获取其RootPath:

 select FileTableRootPath('MyFirstFileTable') as Path

2.RootPath获取后我们就可以在C#程序中实现了,如下代码:

         /// <summary>
/// Upload files by FileTable
/// </summary>
/// <param name="strFilePath">the path of target file</param>
public void UploadbyFileTable(string strFilePath)
{
if (!File.Exists(strFilePath))
return;
FileInfo file = new FileInfo(strFilePath);
string strDBConnection = "Server=your server name/IP,initial catalog=your database name,User id=your id,passord=your password";
string strFileTableName = "your FileTable's name";
string strRootPath = GetFileTableRootPath(strDBConnection, strFileTableName);
if (File.Exists(Path.Combine(strRootPath, file.Name)))
{
return;
}
file.MoveTo(Path.Combine(strRootPath, file.Name));
} /// <summary>
/// Get your Filetable's RootPath
/// </summary>
/// <param name="strDBConnection">your DB connection string</param>
/// <param name="strFileTableName">your FileTable name</param>
/// <returns>your Filetable's RootPath</returns>
public string GetFileTableRootPath(string strDBConnection,string strFileTableName)
{
string strRootPath = string.Empty;
try
{
SqlConnection sqlCon = new SqlConnection(strDBConnection);
sqlCon.Open();
StringBuilder sb = new StringBuilder();
sb.AppendFormat("select FileTableRootPath('{0}') as [path]", strFileTableName);
SqlCommand sqlCmd = new SqlCommand(sb.ToString(), sqlCon);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
strRootPath = dt.Rows[][].ToString();
sqlDa.Dispose();
sqlCmd.Dispose();
sqlCon.Close();
}
catch(Exception e)
{
throw e;
}
return strRootPath;
}

这样就实现了利用FileTable上传文件的功能。到最后,您发现是不是很简单呢?
欢迎您积极提出建议和疑问,我会尽自己的力量给您满意的答复,O(∩_∩)O谢谢

05-06 06:51