前面介紹了怎樣讀取TFS上目錄和文件的信息,怎麼創建服務器和本地的映射(Mapping)。服務器
本節介紹怎樣把TFS服務器上的文件下載到本地。app
下載文件能夠有兩種方式:spa
using Microsoft.TeamFoundation.VersionControl.Client;code
using Microsoft.TeamFoundation.Client;server
方式一:使用VersionControlServer對象,如:對象
string tpcURL = "http://192.168.83.62:8080"; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tpcURL)); VersionControlServer version = tpc.GetService(typeof(VersionControlServer)) as VersionControlServer; version.DownloadFile("$/MySolution", "D:\\TFS\\MySolution"); //從服務器上下載最新版本 VersionSpec spec = new ChangesetVersionSpec(2012); version.DownloadFile("$/MySolution", 0, spec, "D:\\TFS\\MySolution"); //從服務器上下載指定版本 //VersionSpec有以下幾個子類: // ArtifactVersionSpec // LabelVersionSpec // DateVersionSpec // WorkspaceVersionSpec
若是您使用過TFS那麼看到下圖就能明白上面幾個子類的意義了。blog
方式二:使用Microsoft.TeamFoundation.VersionControl.Client.Item對象,如:string
ItemSet items = version.GetItems(serverPath, RecursionType. Full); //最新版 //ItemSet items = version.GetItems(serverPath,spec, RecursionType.OneLevel); //指定版本 foreach (Item item in items.Items) { if (item.ItemType == ItemType.File) { item.DownloadFile(fileFullName); //下載到本地文件 /Stream stream = item.DownloadFile(); //以流的形式返回 } }
從上面的代碼咱們能夠看出服務器上的文件或文件夾能夠下載到本地任意目錄,但在實際應用中,咱們要把它們下載到已作過映射的路徑下。由於沒有映射(Mapping),咱們後期對文件所作的操做就沒法簽入(CheckIn)到服務器。it
結合前面所介紹的Workspace和mapping 咱們來看一段完整的代碼: /// <summary>io
/// 這段代碼從零開始完整地演示了從TFS上下載文件到本地的過程 /// </summary> void DownloadFilesFromTFS() { //第一步:鏈接到TFS服務器 string tpcURL = "http://192.168.83.62:8080"; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tpcURL)); VersionControlServer version = tpc.GetService(typeof(VersionControlServer)) as VersionControlServer; //第二步:建立工做區(Worksapce),若是已經存在就不建立 string worksapce = "WorkSpaceTest01"; Workspace ws; Workspace[] wss = version.QueryWorkspaces(worksapce, Environment.UserName, Environment.MachineName);//查詢工做區 if (wss.Length == 0) { ws = version.CreateWorkspace(worksapce);//建立工做區 } else { ws = wss[0]; }
#region 將$/MySolution/CommDll下的全部文件夾和文件 下載到本地"E:\\TFS62\\MySolution\\CommDll" 下面
string serverPath = "$/MySolution/CommDll"; string savePath = "E:\\TFS62\\MySolution\\CommDll"; //第三步:獲取最新版本,也能夠使用GetItems其餘重載獲取特定版本 ItemSet items = version.GetItems(serverPath, RecursionType.Full); foreach (Item item in items.Items) { string serverItem = item.ServerItem; //如:$/MySolution/CommDll/CommDll.sln string localItem = savePath + serverItem.Substring(serverPath.Length); //存儲到本地的路徑 localItem = localItem.Replace("/", "\\"); //第四步:作映射(Mapping) if (!ws.IsServerPathMapped(serverItem)) { ws.Map(serverItem, localItem); } //第五步:建立目錄或下載文件 if (item.ItemType == ItemType.Folder) { if (!Directory.Exists(localItem)) //若是目錄不存在則建立 { Directory.CreateDirectory(localItem); } } else if (item.ItemType == ItemType.File) { item.DownloadFile(localItem); //下載到本地文件 } } #endregion }