从具有语法的文本文件中获取

时间:2017-04-08 10:40:57

标签: c# winforms text-files

我目前正在开发Windows Form(C#)项目,我需要在多个文本文件中存储信息。这样做可能没问题,我在谷歌上获得了很多结果。但是,我似乎无法根据语法找到从文本文件中排除和包含内容的方法。

程序本身应根据订单中包含的内容创建口头协议。所以我只需要捕获文件的特定部分;即:

NewCustomer.txt

#Introduction#
Today we have decided that you are our customer... Yay!  
-Break-
#BuyFood#
You have decided to buy %foodItem% from us for the price of %priceInDollars% dollars.  
-Break-
#BuyCar#
You have decided to buy a %selectedCar% from us for the price of %priceInDollars% dollars.
-Break-


#Ending#  
My name is %agentName%, thank you for your purchase! 
-Break- 

然后我想从这个文件中提取信息,并在行的弹出窗口行中。这样代理人就会看到类似的东西;

---AGREEMENT-------------------------------------------------|_|[]|X|
| Today we have decided that you are our customer... Yay!           |
| You have decided to buy pizza from us for the price of 12 dollars.|
| My name is Some Dude, thank you for your purchase!                |
|                                                                   |
|                                                             [OK]  |
|___________________________________________________________________|  
然而,

完全卡在这一点上,因为我在以前的任何项目中都没有使用过文本文件或获取函数,所以我不知道从哪里开始。
我该如何完成这样的事情呢?

请注意语法和所有变量都是示例。我不知道这样一个文件的正确语法是什么样的,这就是我创建的向你展示我的想法。

1 个答案:

答案 0 :(得分:1)

如果您想将结构化数据存储为文本,您有两种选择: jSon XML ,在这两种情况下您都不必担心字符串的结构正在创建和解析。你创建了一个类:

public class MyStrings
{
    public int Id { get; set; }
    public string Text { get; set; }
}

然后使用例如NewtonSoft.Json或任何其他Json或XML序列化程序序列化您的数据。

var data = new List<MyStrings>()
{
    new MyStrings()
    {
        Id = 1,
        Text = "Today we have decided that you are our customer... Yay!"
    },
    new MyStrings()
    {
        Id = 2,
        Text = "You have decided to buy {0} from us for the price of {1} dollars."
    }
}

var stringToWriteInFile = JsonConvert.Serialize(data);

结果是一个字符串,您可以在文件中写入,然后执行完全反向以获取数据。