Reputation: 193
I have output in following format
Image Name PID Services
========================= ======== ============================================
System Idle Process 0 N/A
services.exe 436 N/A
svchost.exe 500 BrokerInfrastructure, DcomLaunch, LSM,
PlugPlay, Power, SystemEventsBroker
vnetd.exe 18504 NetBackup Legacy Network Service
I want to store the output in an array like this:
ar[0]=System Idle Process
ar[1]=0
ar[2]=N/A
I tried to split the string on the basis of whitespace but it didnt worked out. Can anyone suggest how to split this and get the desired output in c#
Upvotes: 0
Views: 110
Reputation: 12796
It looks like the information you are receiving has a fixed width output, so, you can just use string.Substring
to get each time a part of the string as you want.
You could read the items in your input like so:
public static IEnumerable<ProcessItem> GetItemsFromText(string text) {
var lines = text.Split( new [] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries );
ProcessItem current = null;
Console.WriteLine( "Lines found: {0}", lines.Length );
// skip first 2 lines (header and = signs)
for (int i = 2; i < lines.Length; i++) {
var name = lines[i].Substring( 0, 25 ).Trim();
var pid = lines[i].Substring( 26, 8 ).Trim();
var services = lines[i].Substring( 35 ).Trim();
if (!string.IsNullOrWhiteSpace( name ) ) {
if (current != null) {
yield return current;
}
current = new ProcessItem {
Name = name,
Pid = pid,
Services = services
};
} else {
current.Services += ' ' + services;
}
}
if (current != null) {
yield return current;
}
}
This version would also acknowledge that you have multi line items, and would send back a custom class ProcessItem
that looks like the following
public class ProcessItem {
public string Name { get; set; }
public string Pid { get;set; }
public string Services { get;set; }
}
A running version of the code you can find back in this .netfiddle
Upvotes: 3
Reputation: 193
use substring on the basis of padding
formatedop[0] = item.Substring(0, 25);
formatedop[1] = item.Substring(25, 10);
formatedop[2] = item.Substring(35, 40);
it will give the result
Upvotes: 1