How to modify an existing file on Github using octokit.net?

1.7k Views Asked by At

This is the code I am using currently. It deletes the contents of the file and replaces it with the new content.

var readfile = client.Repository.Content.GetAllContentsByRef(owner, repo, targetFile, branch).Result;
var updatefile =client.Repository.Content.UpdateFile(owner,repo,targetFile,
new UpdateFileRequest("API File update", "Added this new line new ", readfile.First().Sha, branch));

I want the content to be added to the file. Not replace it. Is there a fault in my code?

1

There are 1 best solutions below

0
On

The Content API is designed to overwrite the contents of a file when you update it, so you need to read the contents of the file and append the new line.

Here's an updated example that you can tailor to suit. Note that the GitHub API will serve up content as Base64 encoded by default.

var currentFileText = "";

var contents = await client.Repository.Content.GetAllContentsByRef(owner, repo, targetFilePath, branch);
var targetFile = contents[0];
if (targetFile.EncodedContent != null)
{
    currentFileText = Encoding.UTF8.GetString(Convert.FromBase64String(targetFile.EncodedContent));
}
else
{
    currentFileText = targetFile.Content;
}

var newFileText = string.Format("{0}\n{1}", currentFileText, "Added this new line");
var updateRequest = new UpdateFileRequest("API File update", newFileText, targetFile.Sha, branch);

var updatefile = await client.Repository.Content.UpdateFile(owner, repo, targetFilePath, updateRequest);