簡體   English   中英

從文本文件C#中讀取文本和變量

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

我有以下代碼嘗試從文本文件中讀取數據(以便用戶可以輕松修改),並根據文本文檔中的單詞以及表單中的變量自動設置段落格式。 我有文件“ body”進入一個字段。 我的正文文本文件中包含以下數據

“內容:” +內容

我希望以此為基礎

內容:項目1、2等

根據我的意見 盡管輸入了“”,但我只能在文本文檔中得到確切的內容。 我究竟做錯了什么? 我希望能得到除文字外的變量。

 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;
        }

如果要為用戶提供自定義文本某些部分的功能,則應使用可以事先搜索並解析出的“指示符”,例如@和@之間的所有內容,讀取為字符串。

您好@道格拉斯先生@,

今天是@DayOfTheWeek @ .....

那時,您的用戶可以替換@和@符號之間的所需內容,然后您將其讀取(例如,使用正則表達式)並將其用作“變量”文本。

讓我知道您是否要這樣做,我可以提供一些C#代碼作為示例。

好的,這是示例代碼:

        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();

這是文本文件的來源:

您好[MrReceiver],

這是來自[公司]的[用戶],使用它作為示例不是很通用:)

[簽名]

希望這可以幫助!

當您從文件中以字符串形式讀取文本時,將獲得文本字符串,僅此而已。

系統的任何部分都不會假設它是C#,可以在當前范圍內對其進行解析,編譯和執行,然后將結果轉換為文本並提供結果。

那基本上不是人們想要的,並且會帶來很大的安全風險-您想要的最后一件事是從程序外部執行任意代碼而沒有任何檢查。

如果需要模板引擎,則需要構建一個模板引擎-例如,讀取字符串,處理字符串以查找關鍵字(例如%content% ,然后將數據添加到它們所在的位置-或找到模板處理庫並將其集成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM