c#文件操作(创建、添加)
需求是对地图服务创建角色,如果sec文件不存在先创建,再新增role;如果sec文件存在,则直接增加role角色。
创建文件:
using (StreamWriter sw = File.CreateText(strSecPath)) { sw.WriteLine("<Permissions>"); sw.WriteLine("\t<Allowed>"); sw.WriteLine("\t\t<Principal>" + arrRoles[j] + "</Principal>"); sw.WriteLine("\t</Allowed>"); sw.WriteLine("\t<Denied>\r\n\t</Denied>"); sw.WriteLine("</Permissions>"); }添加记录: StreamReader srOld = new StreamReader(strSecPath, System.Text.Encoding.Default); int iLineOld = 0; while(srOld.ReadLine()!=null) { iLineOld++; } srOld.Close(); string[] arrNew = new string[iLineOld+1]; StreamReader srNew = new StreamReader(strSecPath, System.Text.Encoding.Default); string strLine = null; int iFlag = -1; while((strLine=srNew.ReadLine())!=null) { iFlag++; if(iFlag<2) { arrNew[iFlag] = strLine; }else { int iLS = iFlag + 1; arrNew[iLS] = strLine; } } arrNew[2] = "\t\t<Principal>" + arrRoles[j] + "</Principal>"; srNew.Close(); File.Delete(strSecPath); using(StreamWriter swNew = File.CreateText(strSecPath)) { for (int m = 0; m < arrNew.Length; m++) { swNew.WriteLine(arrNew[m]); } }