Search code examples
c#gitazure-devopsazure-api-apps

How download file form azure DevOps sever to a specified path using API and c#


I am trying to download a file from azure devops server using API.API give a success response.But no files getting downloaded.If we remove format parameter, we will get response with file link.by clicking that file is not getting downloaded.

sample code

var personalaccesstoken = "ic2pqkzaeqv2dummyTokenDummypa";
                client1.BaseAddress = new Uri("https://dev.azure.com/organisatioTest/ProjectABC");
                client1.DefaultRequestHeaders.Accept.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                   Convert.ToBase64String(
                       System.Text.ASCIIEncoding.ASCII.GetBytes(
                           string.Format("{0}:{1}", "", personalaccesstoken))));
                HttpResponseMessage response1 = client1.GetAsync("_apis/git/repositories/e9e2f082-6f6d-99999b0bcc737a/items?scopePath=/Vjjj/DB/Data/ABC.sql&download=true&$format=zip&api-version=5.1").Result;

Should we add additional c# code to get file download ? How can we specify the download path ?


Solution

  • In C# this URL can be constructed like this (assume the variables are being passed in via a method call):

        var url = $" https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/items?path={path}&api-version=5.1";
    

    With the properly formatted URL we can then make a call to the API using the WebRequest class. For example:

    var request = (HttpWebRequest)WebRequest.Create(address);
    request.UserAgent = "VSTS-Get";
    request.Headers.Set(HttpRequestHeader.Authorization, GetAuthenticationHeaderValue(authentication).ToString());
    request.ContentType = "application/json";
    request.Method = httpMethod;
    response = (HttpWebResponse)request.GetResponse();
    

    Using the HttpWebResponse object we can obtain a Stream object that we can then use to write out the API results to a local file. For example:

    using (var responseStream = GetResponseStream(response))
    {     var fileName = Path.Get Filename(fileToDownload ?? "");     using (var fileStream = File.Create(Path.Combine(destination, fileName)))     {         responseStream.CopyTo(fileStream);     }
    }
    

    Please refer this link for more details: Get file API and sample blog

    Update1

    Thanks sagar for sharing, for more details, please refer to Download a file from azure devops server writes wrong data to the file

    We should try to use Personal access token(PAT).In order to use PAT for authentication we have to use authorization as "Basic" instead of "Bearer".More over instead of adding PAT alone to the Request header we have to use combination of username and PAT.Say base-64-encoded-string of username:PAT.

    Sample code:

    var personalaccesstoken = "wwwwwwwwwwwwwwwwwwy47b7ugkz32bubi64bw7fqdyfpa";
     var base64Creds = Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]:"+ personalaccesstoken));
    request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + base64Creds);