2

Below is an example on how I've been accessing individual files from my public GitHub repository from a console application. Can I do the same for a private repository? I'm not sure how to change the code or if I need to access it with different authorisation settings.

Can anyone tell me what I am doing wrong?

I'm not sure is this will help https://developer.github.com/v3/guides/managing-deploy-keys/

    private static void Main(string[] args)
    {
        var file = $"https://raw.githubusercontent.com/{username}/{repositoryName}/{branch}/{filePath}";

        System.IO.File.WriteAllText($"c:\\{filePath}", GetFile(file));

        System.Console.ReadKey();
    }

    public static string GetFile(string input)
    {
        var output = string.Empty;
        HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(input);

        request.Headers.Add("Authorization", githubtoken);
        request.AllowAutoRedirect = true;

        var response = (HttpWebResponse)request.GetResponse();

        using (var stream = new System.IO.MemoryStream())
        {
            response.GetResponseStream().CopyTo(stream);
            output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
        }

        response.Close();

        return output;
    }

EDIT:

So based on feedback (thanks Olivier), it seems that any use of the githubtoken I used returns either a 403 or 404. My token had read:packages & read:repo_hook and I thought that would be sufficient. I used the following link to show me how to create the token. Do I need anything else to access a private repo with a token?

Can I get access to this via username and password and if so how do I change the above to get a file?

Thundter
  • 582
  • 9
  • 22
  • 2
    *Can I do the same for a private repository?* => did you try and what is the result? –  Sep 27 '19 at 15:38
  • yeah I tried - 'The remote server returned an error: (404) Not Found.' – Thundter Sep 27 '19 at 15:50
  • 1
    Found that: https://stackoverflow.com/questions/15408053/c-sharp-example-of-downloading-github-private-repo-programmatically and https://www.codeproject.com/Articles/1277348/Using-Csharp-Code-to-Access-the-GitHub-API –  Sep 27 '19 at 15:59

2 Answers2

1

I previously had read:packages and read:repo_hook permissions when attempting to access the file and was missing the repo permission. Once supplying that and rerunning the above it started working

I also had to change my url to https://api.github.com/repositories/{repositoryId}/contents/{filePath} and had to add request.UserAgent = githubUsername; to the request before attempting to get a response

Thanks to Olivier Rogier who gave me the clue

Thundter
  • 582
  • 9
  • 22
0

Change the authorization header to this:

request.Headers.Add("Authorization", "token " + githubtoken);

craday
  • 21
  • 3