我的C#类将创建一个GUI,它接收csv文件并相应地绘制线图。目前,我的图表是使用GUI文件对话框绘制和保存的。
我现在要做的是使用命令行读取,绘制并保存图形(不需要GUI)。
我可以知道如何使用“-f”标志调用我的Read和Plot类(文件路径,可以有多个csv文件)并使用“-o”标志保存绘制的图形(输出文件路径,仅生成1个文件)?
感谢。
答案 0 :(得分:0)
您可以使用命令解析器库。命令行解析器(http://commandline.codeplex.com/)非常易于使用。
[Option("f", "input", Required = true]
public string InputFile { get; set; }
[Option("o", "output", Required = true]
public string OutputFile { get; set; }
答案 1 :(得分:0)
如果您正在寻找简单的东西,那么您可以获得一个循环并获得如下值:
string f=null;
string o=null;
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "-f") { f = args[i + 1]; }
else if (args[i] == "-o") { o = args[i + 1]; }
}
if (f != null)
{
}
if (o != null)
{
}
答案 2 :(得分:0)
您可以使用:
课程计划:
static class Program
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")] // ### Edit 3 ###
static extern bool AttachConsole(int dwProcessId); // ### Edit 3 ###
/// <summary>The main entry point for the application.</summary>
[STAThread]
static void Main(string[] args)
{
// redirect console output to parent process;
// must be before any calls to Console.WriteLine()
AttachConsole(-1);// ### Edit 3 ###
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//program.exe -f c:\\desktop\\1.csv -o c:\\desktop\\1.png
var inputFile = new List<string>();
string outputFile = null;
if (args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
string a = args[i].ToLower();
switch (a)
{
case "-f":
for (i = i + 1; i < args.Length ; i++)
{
string f = args[i]; if (f.StartsWith("-")) { i--; break; }
inputFile.Add(f); //get next arg as inputFile
}
break;
case "-o":
outputFile = args[++i]; //get next arg as outputFile
break;
}
}
if (inputFile.Count > 0 && outputFile != null)
{
var form = new Form2(); //specify your form class
form.showErrorsInConsole = true; // ### Edit 3 ###
//form.Visible = true;
form.DoReadFiles(inputFile.ToArray());
form.DoPlot();
form.SavePic(outputFile);
form.Dispose();
return;
}
}
//else
Application.Run(new Form2()); //show GUI
//MessageBox.Show("Args:\r\n" + s);
}
}
表单类(包含图表的表单,在我的代码中为Form2):
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
List<Read> rList = new List<Read>();
public bool showErrorsInConsole = false; //### Edit 3 ###
public void DoReadFiles(string[] fileNames)
{
try
{
rList.Clear();
foreach (String file in fileNames) //if ((myStream = ff.OpenFile()) != null)
{
Read r = new Read(file);
rList.Add(r);
}
}
catch (Exception err)
{
//Inform the user if we can't read the file
if (showErrorsInConsole) //### Edit 3 ###
Console.WriteLine("\r\n *** Error: " + err.Message); //### Edit 3 ###
else
MessageBox.Show(err.Message);
}
}
public void DoPlot(int indX = 0, int indY = 1)
{
Plot.Draw(chart, rList, indX, indY);
}
public void SavePic(string outputFile)
{
bool isPng = outputFile.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
chart.SaveImage(outputFile, isPng ? ChartImageFormat.Png : ChartImageFormat.Jpeg);
}
void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ff = new OpenFileDialog();
ff.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //"C:\\";
ff.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
ff.Multiselect = true;
ff.FilterIndex = 1;
ff.RestoreDirectory = true;
if (ff.ShowDialog() == DialogResult.OK)
{
try
{
DoReadFiles(ff.FileNames);
//Populate the ComboBoxes
if (rList.Count > 0)
{
string[] header = rList[0].header; //header of first file
xBox.DataSource = header;
yBox.DataSource = header.Clone(); //without Clone the 2 comboboxes link together!
}
if (yBox.Items.Count > 1) yBox.SelectedIndex = 1; //select second item
}
catch (Exception err)
{
//Inform the user if we can't read the file
MessageBox.Show(err.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DoPlot(xBox.SelectedIndex, yBox.SelectedIndex);
}
} //end class Form2
课程阅读:
public class Read
{
public int nLines { get; private set; }
public int nColumns { get; private set; }
public string[] header { get; private set; }
public float[,] data { get; private set; }
public string fileName { get; set; }
public string[] section { get; private set; }
public Read(string file)
{
string[] pieces;
fileName = Path.GetFileName(file);
string[] lines = File.ReadAllLines(file); // read all lines
if (lines == null || lines.Length < 2) return; //no data in file
header = lines[0].Split(','); //first line is header
nLines = lines.Length - 1; //first line is header
nColumns = header.Length;
//read the numerical data and section name from the file
data = new float[nLines, nColumns - 1]; // 1 less than nColumns as last col is sectionName
section = new string[nLines];
for (int i = 0; i < nLines; i++)
{
pieces = lines[i + 1].Split(','); // i(+1) is because first line is header
if (pieces.Length != nColumns) { MessageBox.Show("Invalid data at line " + (i + 2) + " of file " + fileName); return; }
for (int j = 0; j < nColumns - 1; j++)
{
float.TryParse(pieces[j], out data[i, j]); //data[i, j] = float.Parse(pieces[j]);
}
section[i] = pieces[nColumns - 1]; //last item
}
}
}
类剧情:
public class Plot
{
public static void Draw(Chart chart, List<Read> rList, int indX = 0, int indY = 1)
{
chart.Series.Clear(); //ensure that the chart is empty
chart.Legends.Clear();
Legend myLegend = chart.Legends.Add("myLegend");
myLegend.Title = "myTitle";
Color[] colors = new Color[] { Color.Black, Color.Blue, Color.Red, Color.Green, Color.Magenta, Color.DarkCyan, Color.Chocolate, Color.DarkMagenta };
var sectionColors = new Dictionary<string, int>();
bool separateSections = (rList.Count == 1); // #Edit: 4
int i = 0;
int iColor = -1, maxColor = -1;
foreach (Read rr in rList)
{
float[,] data = rr.data;
int nLines = rr.nLines;
int nColumns = rr.nColumns;
string[] header = rr.header;
chart.Series.Add("Series" + i);
chart.Series[i].ChartType = SeriesChartType.Line;
chart.Series[i].LegendText = rr.fileName; // #Edit: 4
if (separateSections) chart.Series[i].IsVisibleInLegend = false; // #Edit: 4
chart.ChartAreas[0].AxisX.LabelStyle.Format = "{F2}";
chart.ChartAreas[0].AxisX.Title = header[indX];
chart.ChartAreas[0].AxisY.Title = header[indY];
for (int j = 0; j < nLines; j++)
{
int k = chart.Series[i].Points.AddXY(data[j, indX], data[j, indY]);
if (separateSections) // #Edit: 4
{
string curSection = rr.section[j];
if (sectionColors.ContainsKey(curSection))
{
iColor = sectionColors[curSection];
}
else
{
maxColor++;
iColor = maxColor; sectionColors[curSection] = iColor;
}
chart.Series[i].Points[k].Color = colors[iColor];
}
}
i++; //series#
} //end foreach rr
//fill legend based on series
foreach (var x in sectionColors)
{
string section = x.Key;
iColor = x.Value;
myLegend.CustomItems.Add(colors[iColor], section); //new LegendItem()
}
}
}