将字符串数组转换为进程数组

时间:2018-04-08 09:14:44

标签: c#

我有获取进程列表的服务器,然后将其转换为逗号分隔的字符串,然后发送它。

var processlist = Process.GetProcesses();
string sendata = string.Join(",", processlist.Select(c => c.ToString()).ToArray<string>());
writer.WriteLine(sendata);
writer.Flush();

现在另一方面,我收到字符串,然后将其更改为string[]

string[] split = response.Split(',');

现在我该如何将其从string[]更改回Process[]

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?注意我没有尝试编译它。

您必须复制Process的所有属性并通过线路传输它们。另一方面,您可以获取显示的属性及其值,但您将没有真正的Process对象。

public struct PropertyValue {
    public PropertyValue( string propertyName, string value) 
    { 
        this.PropertyName = propertyName;
        this.Value = this.value;
    }
    private PropertyValue( params string[] pv) => PropertyValue(pv[0], pv[1]);
    public string PropertyName {get;}
    public string Value {get;}
    override public string ToString() => this.PropertyName + ":" + this.Value;
    public static PropertyValue FromString(string pv) => return new PropertyValue( pv.Split(":"));
}

然后

public string ToString( Process process) {
    var msg = new StringBuffer();
    foreach (PropertyInfo property in process.GetProperties()) {
         var propertyValue = new PropertyValue( property.Name, property.GetValue( process));
         msg.Append( ((msg.Length > 0)? ",": "") + propertyValue.ToString());
    }
    return msg.ToString();
}

public PropertyValue[] FromString( string msg) 
{
    string[] pvStrings = msg.Split(",");
    PropertyValue[] propertyValues = new PropertyValue[pvStrings.Length];
    int i = 0;
    foreach (string pvString in pvStrings) {
        propertyValues[i] = FromString( pvString);
    }
    return propertyValues;
}