批量下載TFS工作項附件

以單個工作項示例:工作項ID可以從數據庫或者其他文件中讀取

-----------

using System.IO;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Net;

namespace TestFileStream
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection sqlConnection = new SqlConnection(
                "Integrated Security=true;server=數據庫服務器名稱;database=對應的tfs數據庫");
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = sqlConnection;            
            string sql = "SELECT  *  FROM  WorkItemFiles  WHERE  id='工作項ID' ";
            SqlDataAdapter sda = new SqlDataAdapter(sql, sqlConnection);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string fileId = row["ExtID"].ToString();
                    string fileName = row["OriginalName"].ToString();
                    DownLoadFile("工作項ID", fileName, fileId);
                }
            }
        }

        public static void DownLoadFile(string WorkItemId,string fileName, string fileId)
        {
		    //手工分析項目中的附件鏈接
            string filePath = "http://*****/attachfilehandler.ashx?fileid=" + fileId;
            WebRequest req = WebRequest.Create(filePath);
            WebClient wc = new WebClient();
            wc.UseDefaultCredentials = true;
            wc.Credentials = new NetworkCredential("帳號", "密碼", "域名");
            wc.DownloadData(filePath);
            Stream str = wc.OpenRead(filePath);
            // 初始化一個緩存區
            byte[] buffer = new byte[1024];
            int read = 0;
            int block;
            while ((block = str.Read(buffer, read, buffer.Length - read)) > 0)
            {
                read += block;
                if (read == buffer.Length)
                {               
                    int nextByte = str.ReadByte();              
                    if (nextByte == -1)
                    {
                        break;
                    }                
                    byte[] newBuf = new byte[buffer.Length * 2];
                    Array.Copy(buffer, newBuf, buffer.Length);
                    newBuf[read] = (byte)nextByte;                   
                    buffer = newBuf;
                    read++;
                }
            }
            byte[] ret = new byte[read];
            Array.Copy(buffer, ret, read);
            //文件寫入本地指定的文件夾,文件名稱:"工作項ID_文件ID_文件名"
            FileStream fstr = new FileStream("f:\\Test\\" + WorkItemId + "_" + fileId + "_" + fileName, FileMode.Create, FileAccess.Write);
            fstr.Write(ret, 0, ret.Length);
        }
    }
}

VSTS,SVN,TFS,SqlServer,版本控制,源碼管理,bug管理,需求管理,TFS2010 交流羣

羣號:197992930  #點擊加羣#19  71999293019799

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章