Create new repo in Github Server from C#

744 views Asked by At

I need a help to create new git repo in github(Web) from my C#. I have already used lib2gitsharp dll to communicate to Github but where I can create a repo in local (i.e. kind of working copy) not sure how to create the same in Web / remote server.

2

There are 2 answers

0
Kluddizz On BEST ANSWER

libgit2sharp is a git protocol implementation, not an API for GitHub. Therefore requests based on the GitHub API are not implemented. Read this issue.

You can use the octokit library to do so. Based on Octokit.net Creating new repository you can create a new repository using the following statements.

using Octokit;

// Authentification
var basicAuth = new Credentials(Owner, Password);
var Client = new GitHubClient(new ProductHeaderValue("my-cool-app"));
Client.Credentials = basicAuth;

// Create 
try {
    var repository = new NewRepository(RepositoryName) {
        AutoInit = false,
        Description = "",
        LicenseTemplate = "mit",
        Private = false
    };
    var context = Client.Repository.Create(repository);
    RespositoryGitHub = context.Result;
    Console.WriteLine($"The respository {RepositoryName} was created.");
} catch (AggregateException e) {
    Console.WriteLine($"E: For some reason, the repository {RepositoryName}  can't be created. It may already exist. {e.Message}");
    }
}
1
Shivam Patel On
    /// <summary>
/// Used to create new repository if  now exist remotely
/// </summary>
/// <param name="ownername"></param>
/// <param name="accesstoken"></param>
/// <param name="repositoryname"></param>
/// <returns></returns>
private string CreateNewGithubRepo(string ownername, string accesstoken, string repositoryname)
{

    var basicAuth = new Octokit.Credentials(ownername, accesstoken);
    var Client = new GitHubClient(new Octokit.ProductHeaderValue("my-app"));
    Client.Credentials = basicAuth;

    // Create 
    try
    {
        var repository = new NewRepository(repositoryname)
        {
            AutoInit = false,
            Description = "",
            LicenseTemplate = "mit",
            Private = false
        };

        var context = Client.Repository.Create(repository);
        Octokit.Repository RespositoryGitHub = context.Result;
        return string.Empty;
    }
    catch (AggregateException e)
    {
        return $"\nE: For some reason, the repository {repositoryname}  can't be created. It may already exist. {e.Message}";
    }
    catch (Exception e)
    {
        return $"\nSom`enter code here`ething went wrong. The repository {repositoryname}  can't be created.  {e.Message}";
    }
}