简体   繁体   English

从文本文件C#中读取文本和变量

[英]Reading text and variables from text file c#

I have the following code which tries to read data from a text file (so users can modify easily) and auto format a paragraph based on a the words in the text document plus variables in the form. 我有以下代码尝试从文本文件中读取数据(以便用户可以轻松修改),并根据文本文档中的单词以及表单中的变量自动设置段落格式。 I have the file "body" going into a field. 我有文件“ body”进入一个字段。 my body text file has the following data in it 我的正文文本文件中包含以下数据

"contents: " + contents “内容:” +内容

I was hoping based on that to get 我希望以此为基础

contents: Item 1, 2, etc. 内容:项目1、2等

based on my input. 根据我的意见 I only get exactly whats in the text doc despite putting "". 尽管输入了“”,但我只能在文本文档中得到确切的内容。 What am I doing wrong? 我究竟做错了什么? I was hoping to get variables in addition to my text. 我希望能得到除文字外的变量。

 string readSettings(string name)
        {
            string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Yuneec_Repair_Inv";

            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(path + "/" + name + ".txt"))
                {
                    string data = sr.ReadToEnd();
                    return data;
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The settings file for " + name + " could not be read:");
                Console.WriteLine(e.Message);
                string content = "error";
                return content;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            createSettings("Email");
            createSettings("Subject");
            createSettings("Body");

            yuneecEmail = readSettings("Email");
            subject = readSettings("Subject");
            body = readSettings("Body");           

        }

 private void button2_Click(object sender, EventArgs e)
        {
            bodyTextBox.Text = body;
        }

If you want to provide the ability for your users to customize certain parts of the text you should use some "indicator" that you know before hand, that can be searched and parsed out, something like everything in between @ and @ is something you will read as a string. 如果要为用户提供自定义文本某些部分的功能,则应使用可以事先搜索并解析出的“指示符”,例如@和@之间的所有内容,读取为字符串。

Hello @Mr Douglas@, 您好@道格拉斯先生@,

Today is @DayOfTheWeek@..... 今天是@DayOfTheWeek @ .....

At that point your user can replace whatever they need in between the @ and @ symbols and you read that (for example using Regular Expressions) and use that as your "variable" text. 那时,您的用户可以替换@和@符号之间的所需内容,然后您将其读取(例如,使用正则表达式)并将其用作“变量”文本。

Let me know if this is what you are after and I can provide some C# code as an example. 让我知道您是否要这样做,我可以提供一些C#代码作为示例。

Ok, this is the example code for that: 好的,这是示例代码:

        StreamReader sr = new StreamReader(@"C:\temp\settings.txt");
        var set = sr.ReadToEnd();
        var settings = new Regex(@"(?<=\[)(.*?)(?=\])").Matches(set);
        foreach (var setting in settings)
        {
            Console.WriteLine("Parameter read from settings file is " + setting);
        }
        Console.WriteLine("Press any key to finish program...");
        Console.ReadKey();

And this is the source of the text file: 这是文本文件的来源:

Hello [MrReceiver], 您好[MrReceiver],

This is [User] from [Company] something else, not very versatile using this as an example :) 这是来自[公司]的[用户],使用它作为示例不是很通用:)

[Signature] [签名]

Hope this helps! 希望这可以帮助!

When you read text from a file as a string, you get a string of text, nothing more. 当您从文件中以字符串形式读取文本时,将获得文本字符串,仅此而已。

There's no part of the system which assumes it's C#, parses, compiles and executes it in the current scope, casts the result to text and gives you the result of that. 系统的任何部分都不会假设它是C#,可以在当前范围内对其进行解析,编译和执行,然后将结果转换为文本并提供结果。

That would be mostly not what people want, and would be a big security risk - the last thing you want is to execute arbitrary code from outside your program with no checks. 那基本上不是人们想要的,并且会带来很大的安全风险-您想要的最后一件事是从程序外部执行任意代码而没有任何检查。

If you need a templating engine, you need to build one - eg read in the string, process the string looking for keywords, eg %content% , then add the data in where they are - or find a template processing library and integrate it. 如果需要模板引擎,则需要构建一个模板引擎-例如,读取字符串,处理字符串以查找关键字(例如%content% ,然后将数据添加到它们所在的位置-或找到模板处理库并将其集成。

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

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