连接到tfs并下载VS2010中存在的文件

时间:2015-09-08 09:04:15

标签: c# visual-studio-2010 tfs

我想连接到TFS并下载其中的文件。我正在使用VS2010并尝试以下代码。但似乎我在某处出错:

  

"非静态场方法需要一个对象引用" for GetItem()和CopyTo()方法

我的代码没有下载所有文件。

C#代码:

static void Main(string[] args)
    {
        string teamProjectCollectionUrl = "https://YourTfsUrl/tfs/YourTeamProjectCollection";
        string filePath = "C:\project\myfile.cs";

        TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
        VersionControlServer versionControlServer = teamProjectCollection.GetService<VersionControlServer>();

        Item item = versionControlServer.GetItem(filePath, VersionSpec.Latest);

        string fileString = string.Empty;

        using (Stream stream = item.DownloadFile())
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);


                using (StreamReader streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray())))
                {
                    fileString = streamReader.ReadToEnd();
                }
            }
        }

        Console.WriteLine(fileString);
        Console.ReadLine();
    }

有人可以帮我找到合适的方法吗?

1 个答案:

答案 0 :(得分:4)

尝试这样的事情......

    static void Main(string[] args)
    {
        string teamProjectCollectionUrl = "http://myserver:8080/tfs/DefaultCollection";
        string serverPath = "$/My Project/My SubFolder";
        string localPath = @"c:\temp\download";

        TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
        VersionControlServer versionControlServer = teamProjectCollection.GetService<VersionControlServer>();

        foreach (Item item in versionControlServer.GetItems(serverPath, VersionSpec.Latest, RecursionType.Full, DeletedState.NonDeleted, ItemType.Any, true).Items)
        {
            string target = Path.Combine(localPath, item.ServerItem.Substring(2));

            if (item.ItemType == ItemType.Folder && !Directory.Exists(target))
            {
                Directory.CreateDirectory(target);
            }
            else if (item.ItemType == ItemType.File)
            {
                item.DownloadFile(target);
            }
        }
    }