我将c#应用程序表单与文本文件连接起来。但我不希望它被硬编码。 到目前为止,我在文件中的代码如下所示。我不想显示文件名和路径文件。我宁愿让它放入app.config文件并从app.config filw中使用它。你能告诉我在这个文件和app.config文件中我要做哪些更改:
private void button1_Click(object sender, EventArgs e)
{
string sqlConnectionString = @"C:\Jaspreet_Files\LoadOrgInPortal.txt";
var fileContents = System.IO.File.ReadAllText(@"C:\Jaspreet_Files\LoadOrgInPortal.txt");
fileContents = fileContents.Replace("{param_1}", textBox1.Text.ToString());
fileContents = fileContents.Replace("{param_2}", textBox2.Text.ToString());
fileContents = fileContents.Replace("{param_3}", textBox3.Text.ToString());
fileContents = fileContents.Replace("{param_4}", textBox4.Text.ToString());
System.IO.File.WriteAllText(@"C:\Jaspreet_Files\NewLoadOrgInPortal.txt", fileContents);
Application.Exit();
}
我的app.config文件目前是空的。我的意思是我还没有做任何编码。
答案 0 :(得分:1)
应用程序设置非常简单。
将您的属性添加到App.Config应用设置中,例如
<appSettings>
<add key="sqlConnectionString" value="C:\Jaspreet_Files\LoadOrgInPortal.txt" />
</appSettings>
..并阅读它们,例如
var sqlConnectionString = System.Configuration.ConfigurationSettings.AppSettings["sqlConnectionString"];
答案 1 :(得分:0)
using System;
using System.Collections.Specialized;
using System.Configuration;
...
...
...
private void button1_Click(object sender, EventArgs e)
{
AppSettingsReader reader = new AppSettingsReader();
string txtFilePath = (string)reader.GetValue("txtFilePath", typeof(string));
//string sqlConnectionString = @"C:\Jaspreet_Files\LoadOrgInPortal.txt";
string sqlConnectionString = txtFilePath;
//var fileContents = System.IO.File.ReadAllText(@"C:\Jaspreet_Files\LoadOrgInPortal.txt");
var fileContents = System.IO.File.ReadAllText(txtFilePath);
fileContents = fileContents.Replace("{param_1}", textBox1.Text.ToString());
fileContents = fileContents.Replace("{param_2}", textBox2.Text.ToString());
fileContents = fileContents.Replace("{param_3}", textBox3.Text.ToString());
fileContents = fileContents.Replace("{param_4}", textBox4.Text.ToString());
System.IO.File.WriteAllText(@"C:\Jaspreet_Files\NewLoadOrgInPortal.txt", fileContents);
Application.Exit();
}