简体   繁体   中英

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. 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.

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@.....

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.

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],

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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