在c#中写入linux tty(/ dev /)文件

时间:2015-07-22 18:13:12

标签: c# linux file mono tty

我需要我的程序执行一个命令,在Bash中看起来像这样: " echo P1-12 = 175>的/ dev / servoblaster&#34 ;.我如何在Linux上的Mono / C#中执行此操作?我写了以下课程:

public static class ServoBlasterPWM
{
    private static FileStream devFile;

    public static bool IsRunning
    {
        get;
        private set;
    }

    public static bool Initialize()
    {
        try
        {
            devFile = File.Open("/dev/servoblaster", FileMode.Open);
        }
        catch (Exception e)
        {
            Log.Error("Error while setting up port for Servo Blaster: " + e.Message);
            return false;
        }

        Log.Success("ServoBlaster is set up.");
        IsRunning = true;

        return true;
    }

    public static void SetPWMOutput(int pin, int valueSteps)
    {
        //byte[] bytes = Encoding.ASCII.GetBytes("P1-" + pin.ToString() + "=" + valueSteps.ToString());

        byte[] bytes = Encoding.ASCII.GetBytes("P1-12=175");
        devFile.Write(bytes, 0, bytes.Length);
        devFile.Flush();

        Console.WriteLine("Wrote to file");
    }

    public static void Shutdown()
    {
        devFile.Close();
        IsRunning = false;

        Log.Info("Servo Blaster has been shut down.");
    }
}

此代码不起作用。我也尝试过StreamWriter而不是FileStream,但它崩溃了一个例外,说流不支持搜索。我不知道该怎么做。请帮忙。

1 个答案:

答案 0 :(得分:0)

尝试将字符串替换为数组代码:

byte[] bytes = ASCIIEncoding.UTF8.GetBytes("P1-12=175") ;

或:

byte[] bytes = ASCIIEncoding.Default.GetBytes("P1-12=175") ;