03-17-2024, 01:27 PM
I have been using the following PowerShell code to upload images to GitHub, and it works well.
Embedding PowerShell code in LA also works successfully, but the execution speed is slow.
Therefore, I attempted to convert the PowerShell code to generic C# code using ChatGPT. However,
it always reports errors when executed. Is there a simpler solution to use LA functions?
Powershell:
Embedding PowerShell code in LA also works successfully, but the execution speed is slow.
Therefore, I attempted to convert the PowerShell code to generic C# code using ChatGPT. However,
it always reports errors when executed. Is there a simpler solution to use LA functions?
// script "img2github.cs"
/*/ nuget -\Newtonsoft.json; /*/ //.
using System.Net;
script.setup(trayIcon: true, sleepExit: true);
//..
string token = "ghp_XXXX"; // GitHub Token
string owner = "XXX"; // Owner of the repository
string repo = "XXX.github.io"; // Repository name
string file = folders.Desktop + "\\A.png"; // File path of the image
string path = $"Temp/A.png"; // Path of the image in the repository
string content = Convert.ToBase64String(File.ReadAllBytes(file));
string url = $"https://api.github.com/repos/{owner}/{repo}/contents/{path}";
WebClient client = new WebClient();
client.Headers.Add("Accept", "application/vnd.github+json");
client.Headers.Add("Authorization", $"Bearer {token}");
client.Headers.Add("X-GitHub-Api-Version", "2022-11-28");
//Please modify with your own GitHub account name and email address
string json = $@"{{
""message"": ""Update: {path}"",
""committer"": {{
""name"": ""XXXXX"",
""email"": ""XXXXX""
}},
""content"": ""{content}""
}}";
byte[] requestData = Encoding.UTF8.GetBytes(json);
byte[] responseData = client.UploadData(url, "PUT", requestData);
string responseJson = Encoding.UTF8.GetString(responseData);
// Parse the response JSON to get the download URL
dynamic response = Newtonsoft.Json.JsonConvert.DeserializeObject(responseJson);
string downloadUrl = response.content.download_url;
Console.WriteLine(downloadUrl);
Powershell:
$token = "ghp_XXXX" # GitHub Token
$owner = "XXX" # Owner of the repository
$repo = "XXX.github.io" # Repository name
$file = "$HOME\Desktop\A.png" # File path of the image
$path = "Temp/A.png" # Path of the image in the repository
$Content = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($file))
$url = "https://api.github.com/repos/$owner/$repo/contents/$path"
$headers = @{
Accept = "application/vnd.github+json"
Authorization = "Bearer $token"
"X-GitHub-Api-Version" = "2022-11-28"
}
#Please modify with your own GitHub account name and email address
$body = @{
message = "Update: $path"
committer = @{
name = "XXXXX"
email = "XXXXX"
}
content = $Content
} | ConvertTo-Json
$response = Invoke-RestMethod -Method Put -Uri $url -Headers $headers -Body $body
$response.content.download_url