using System.Collections.Generic;
using System.Diagnostics;
static string wifiFilePath = @"/etc/network_profiles/wifi/profiles.json";
CommandLineProcessor _processor;
_processor = new CommandLineProcessor();
var networkProfile = new WifiNetworkProfile
Password = "redballoon924",
AddWifiNetworkProfile(networkProfile);
private void AddWifiNetworkProfile(WifiNetworkProfile networkProfile)
var contents = ReadFromFile(wifiFilePath);
Console.WriteLine($"Contents: {contents}");
var profiles = SerializationHelper.DeserializeContent<List<WifiNetworkProfile>>(contents);
profiles.Add(networkProfile);
var jsonString = SerializationHelper.SerializeContent(profiles);
Console.WriteLine($"JSON.String: {jsonString}");
WriteToFile(jsonString, wifiFilePath);
private string ReadFromFile(string filepath)
CreateFileIfNotExists(wifiFilePath);
var args = $"sudo cat {filepath}";
var processResult = _processor.ProcessBashCommand(args);
return processResult.OutputResult;
private void WriteToFile(string content, string filepath)
CreateFileIfNotExists(wifiFilePath);
var args = $"echo {content} | sudo tee {filepath}";
_processor.ProcessBashCommand(args);
private void CreateFileIfNotExists(string filepath)
var args = $"[ ! -f {filepath}] && sudo touch {filepath}";
_processor.ProcessBashCommand(args);
public class CommandLineProcessor
private readonly int _timeoutPeriod = 15000;
public ProcessResult ProcessBashCommand(string args)
var escapedArgs = args.Replace("\"", "\\\"");
var process = new Process
StartInfo = new ProcessStartInfo
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
var outputResult = process.StandardOutput.ReadToEnd();
process.WaitForExit(_timeoutPeriod);
var exitCode = process.ExitCode;
return new ProcessResult { OutputResult = outputResult, ExitCode = exitCode };
return new ProcessResult { OutputResult = "err", ExitCode = -1 };
public class ProcessResult
public string OutputResult { get; set; }
public int ExitCode { get; set; }
public class WifiNetworkProfile : INetworkProfile
public NetworkType NetworkType => NetworkType.Wifi;
public int Priority { get; set; }
public string SSID { get; set; }
public string Password { get; set; }
public interface INetworkProfile
NetworkType NetworkType { get; }
int Priority { get; set; }
public static class SerializationHelper
public static string SerializeContent<T>(T value)
return JsonConvert.SerializeObject(value, GetJsonSerializerSettings());
public static T DeserializeContent<T>(string value)
return JsonConvert.DeserializeObject<T>(value, GetJsonSerializerSettings());
private static JsonSerializerSettings GetJsonSerializerSettings()
return new JsonSerializerSettings
Formatting = Formatting.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.All,
NullValueHandling = NullValueHandling.Include