今天的工作就是動態產生一個檔案,根據使用者佈建的不同,產生的檔案也不同。其實要產生的檔案是一個文字檔,常值內容是.aspx.cs的代碼。
已經為檔案寫好了一個範例,並且把一些需使用者佈建的值當作變數,放在了需要更改的地區,使用者修改之後,只需要把這些變數的值更改一下即可。
範例代碼剪下:
protected System.Web.UI.WebControls.Button BTSearch;
protected System.Web.UI.WebControls.TextBox TBSearch;
protected System.Web.UI.WebControls.DropDownList Community;
//以下就是需更改的地區
//--Begin--
protected string pageid="10";
protected string tablename="LJF";
protected ArrayList al=new ArrayList();
protected void SetArrayList()
{
al.Clear();
al.Add("居委會名稱");
al.Add("垃圾房位置");
}
//--End--
protected void CheckDelete(object sender,System.EventArgs e)
{
((LinkButton)sender).Attributes.Add("onclick","return IsDelete();");
}
需更改的地方,以//--Begin開始,以//--End--結束。
但是,很麻煩,找協助找了幾個小時,發現在C#中StreamWriter類,FileStream類好像只支援簡單的對檔案進行寫入,讀出工作。要把中間那一段需修改的字串抽取出來,修改後,再儲存回該檔案,我沒辦到!
後來,找到了一個解決辦法,就是,把檔案全部讀出來,放到String對象中去,String類中對字串的操作可強多了。以下是解決的代碼: string path=@"D:\browser.aspx.cs";
StreamReader sr = new StreamReader(path,Encoding.Default); //把檔案讀到流中
string allstr = sr.ReadToEnd(); //檔案中的內容放入String對象allstr中
sr.Close();
//下面先把檔案分割出來,然後填入相應的設定的變數進去,最後進行整合。
//剝離檔案--頭部分
int begin=allstr.IndexOf("//--Begin--")+11;
string strBegin = allstr.Substring(0,begin);
//剝離檔案--尾部分
int end = allstr.IndexOf("//--End--");
string strEnd = allstr.Remove(0,end);
//設定尾碼代碼中需修改變數的值
string strmodify="protected string pageid=\""+spageid+"\";\n";
strmodify=strmodify+"protected string tablename=\""+stablename+"\";\n";
strmodify=strmodify+"protected ArrayList al=new ArrayList();\n";
strmodify=strmodify+"protected void SetArrayList()\n";
strmodify=strmodify+"{ al.Clear();\n";
string strmodify2="";
for(int i=0;i<sserach.Count;i++)
{
strmodify2=strmodify2+"al.Add(\""+sserach[i].ToString()+"\");\n";
}
strmodify=strmodify+strmodify2;
strmodify=strmodify+"}\n";
//再把修改後的檔案儲存
StreamWriter sw = File.CreateText(sfolder+"\browser.aspx.cs");
sw.Write(strBegin+strmodify+strEnd); //頭部分+修改後的文本+尾部分=修改後的代碼
sw.Close();
至此,棘手的問題解決,Happy~~~