前面介紹了怎樣讀取TFS上目錄和文件的信息,怎么建立服務器和本地的映射(Mapping)。
本節介紹怎樣把TFS服務器上的文件下載到本地。
下載文件可以有兩種方式:
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Client;
方式一:使用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那么看到下圖就能明白上面幾個子類的意義了。
方式二:使用Microsoft.TeamFoundation.VersionControl.Client.Item對象,如:
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)到服務器。
結合前面所介紹的Workspace和mapping 我們來看一段完整的代碼:/// <summary>
/// 這段代碼從零開始完整地演示了從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("/", "http://"); //第四步:做映射(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}新聞熱點
疑難解答