When attempting to run Azure CLI commands through a C# Console Application, an exception is encountered. While there are no build errors, the execution of the project results in an error.
Here is a snapshot of the error I encountered:
Here is the C# code I am attempting to run.
using System;
using System.Diagnostics;
using System.IO;
public class AzureCliCommandRunner
{
public static string RunAzureCliCommand(string command)
{
var processStartInfo = new ProcessStartInfo
{
FileName = "az",
Arguments = command,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = processStartInfo })
{
process.Start();
// Read the output and error streams
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode == 0)
{
return output;
}
else
{
// Handle the error
throw new InvalidOperationException($"Command execution failed. Error: {error}");
}
}
}
public static void UpdateAppConfigFilter(string endpoint, string featureName)
{
// Run Azure CLI commands to update AppConfig filter
string command1 = $"appconfig feature filter show --connection-string {endpoint} --feature {featureName} --filter-name Microsoft.Targeting";
string jsondata = RunAzureCliCommand(command1);
string command2 = $"echo '{jsondata}' | jq -r '.[].parameters.Audience'";
string audienceSection = RunAzureCliCommand(command2).Trim();
string new_user = "newuser";
string command3 = $"echo '{audienceSection}' | jq --arg new_user '{new_user}' '.Users += [\"$new_user\"]'";
string file_content = RunAzureCliCommand(command3).Trim();
string command4 = $"appconfig feature filter update --connection-string {endpoint} --feature {featureName} --filter-name Microsoft.Targeting --filter-parameters Audience='{file_content}' --yes";
RunAzureCliCommand(command4);
}
public static void Main()
{
// Replace <<EndPoint>> and <<FeatureName>> with your actual values
string endpoint = <<EndPoint>>;
string featureName = <<FeatureName>>";
UpdateAppConfigFilter(endpoint, featureName);
}
}
Firstly, i too got similar error, Here Filename should be changed to a place where az.cmd is located in your system.
I modified your code a bit as below:
Output: