有一個需求:當管理員登錄時,可以對上傳文件目錄的修改,它的那個文件上傳路徑已經放到配置文件
App.config文件中了,如下代碼:
<appSettings>
<add key="Version" value="1.0.0" />
<add key="FileUploadPath" value="//192.168.0.103/UploadFolder/aaa32000)" />
</appSettings>
也就是說我要修改xml文件的節點值,
首先我們要找到文件App.config文件如下代碼:
string filePath = new DirectoryInfo(Application.StartupPath).Parent.Parent.FullName +
"//App.Config";
然後再找到文件中要修改的節點,如下代碼初始化路徑文本框的文本
private void initFilePath()
{
//建立一個XmlDocument對象
XmlDocument webconfigDoc = new XmlDocument();
//找到節點的xml路徑
string xPath = "/configuration/appSettings/add[@key='FileUploadPath']";
//加載web.config文件
webconfigDoc.Load(filePath);
////讀出路徑放到txtfilepath文本框中
XmlNode passkey = webconfigDoc.SelectSingleNode(xPath);
string filepathtxt = passkey.Attributes["value"].InnerText.Replace
("//192.168.0.103//","");
this.txtFilePath.Text=filepathtxt;
}
然後我們對“保存”按鈕寫事件
private void btnSave_Click(object sender, EventArgs e)
{
try
{
XmlDocument webconfigDoc = new XmlDocument();
//設置節的xml路徑
string xPath = "/configuration/appSettings/add[@key='FileUploadPath']";
//加載web.config文件
webconfigDoc.Load(filePath);
//找到要修改的節點
XmlNode passkey = webconfigDoc.SelectSingleNode(xPath);
//判斷字符串路徑合法性的正則表達式。
string expre = @"^(//[^///:*?""<>|]+)+//?$";
if (ExecuteValidator(txtFilePath.Text.Trim(), expre))
{
DirectoryInfo dir = new DirectoryInfo(txtFilePath.Text.Trim().Replace
("////","//"));
//設置節點的值
passkey.Attributes["value"].InnerText = "//" + "//192.168.0.103" + dir;
//創建目錄
if (Directory.Exists("//" + "//192.168.0.103" + dir))
{
}
else
{
Directory.CreateDirectory("//" +
"//192.168.0.103"+txtFilePath.Text);
}
//保存設置
webconfigDoc.Save(filePath);
MessageBox.Show("保存成功");
}
else
{
MessageBox.Show("格式不正確,格式應爲:////server//share");
}
}
catch (Exception ee)
{
MessageBox.Show("保存不成功,"+ee.Message);
}
}
public bool ExecuteValidator(string str, string Expression)
{
try
{
Regex r = new Regex(Expression);//創建正則表達式。
return r.Match(str).Success;//進行驗證。
}
catch
{
return false;
}
}
總結:這個需求沒有什麼技術難點,其中有一個隱含的東西就是當我寫的路徑不存在時,它也能修改配
置文件,但是事實這個目錄是不存在的,那樣會導致程序出錯,也就是說我們還要對你寫的路徑,進行
創建目錄,這樣的話就能滿足客戶的需求,不用到時候還要手動去硬盤上建一個目錄。
還有一個要注意的地方就是我們是在文本框中寫字符串路徑,它的合法性我們也要驗證,用
DirectoryInfor類時,它能驗證一些特殊字符如:“<”,“?”,“*”等等,但aa////bbb能通過,這
樣用戶體驗就不是特別好了,所以我們寫了一個正則表達式來驗證文本字符串路徑的合法性,這樣才能
達到用戶體驗好的效果。
我們代碼不一定是優化的,我希望更多的人來優化一下代碼,共同進步嘛。