简体   繁体   English

将一行“数据”从一个C#控制台应用程序传递到另一个C#控制台应用程序的最佳方法是什么?

[英]What's the best way to pass a “row of data” from one C# console app to another C# console app?

I have a C# console app "App1" that reads a row of data from a table in a SQL Server 2005 DB. 我有一个C#控制台应用程序“App1”,它从SQL Server 2005数据库中的表中读取一行数据。 I want App1 to pass all the data in this row to App2, another C# console app. 我希望App1将此行中的所有数据传递给另一个C#控制台应用App2。 What is the best way to do this? 做这个的最好方式是什么?

My first (naive) attempt was to do this: 我的第一次(天真)尝试是这样做的:

object[] o = myrow.ItemArray;
// make a string that separates each item by a space... for example "1 2 myVar".
// pass this string to App2 via command line.

This has some flaws: what if one of the entries in the row was "my var" instead of "myVar"? 这有一些缺陷:如果行中的一个条目是“my var”而不是“myVar”怎么办? Also, the order of the items would be hardcoded in the receiving app (App2). 此外,项目的顺序将在接收应用程序(App2)中进行硬编码。

So what's the best way to do this? 那么最好的方法是什么? Would it be appropriate to pass an xml string to App2 via command line? 是否适合通过命令行将xml字符串传递给App2?

Cheers! 干杯!

One approach would be to serialize the row to XML and use that, except that DataRow (lacking a default constructor) can't be serialized. 一种方法是将行序列化为XML并使用它,除了DataRow(缺少默认构造函数)无法序列化。 Instead you'd have to create a new DataTable and add that row to it. 相反,您必须创建一个新的DataTable并将该行添加到其中。

Then you could simply serialize the entire DataTable to XML and pass it to the other application, either as a command-line argument or by saving the XML to a file and passing the filename. 然后,您可以简单地将整个DataTable序列化为XML并将其作为命令行参数传递给另一个应用程序,或者将XML保存到文件并传递文件名。

Serializing a DataTable to XML is quite trivial thanks to the DataTable.WriteXml method. 由于DataTable.WriteXml方法,将DataTable序列化为XML非常简单。

The space-separated approach is fine if you are using Process.Start - you just need to wrap items containing spaces with quotes - same as at the command line: cd "c:\\program files" 如果使用Process.Start,则以空格分隔的方法很好 - 您只需要包含带引号的空格的项目 - 与命令行相同:cd“c:\\ program files”

If the data is more complex than a few values, then IPC approaches such as remoting, sockets, WCF, etc might help. 如果数据比几个值更复杂,那么诸如远程处理,套接字,WCF等IPC方法可能会有所帮助。 Or simpler: write the data (perhaps as xml) to a file, and have the second app load the data from the file. 或者更简单:将数据(可能是xml)写入文件,让第二个应用程序加载文件中的数据。

You could use a serialized DataSet to easily get the data from one place to another without having to write a lot of custom code, as the default DataSet already provides the necessary methods ( .WriteXML for example will serialize the DataSet to XML and write to a file). 您可以使用序列化DataSet轻松地将数据从一个地方传送到另一个地方而无需编写大量自定义代码,因为默认DataSet已经提供了必要的方法(例如.WriteXML将DataSet序列化为XML并写入文件)。 Your other application could then poll the appropriate directory for new files. 然后,您的其他应用程序可以在适当的目录中轮询新文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM