asp.net(c#)如何讀取上傳過程中的.txt檔案中的資料,並將其寫入資料庫的
來源:互聯網
上載者:User
private void ReadFile(string path)
{
if(System.IO.File.Exists(path))//判斷指定路徑的檔案是否存在
{
StreamReader reader=new StreamReader(path,System.Text.Encoding.GetEncoding("GB2312"));
//執行個體化一個StreamReader ,並且指定編碼方式,不然讀取中文的時候會出現亂碼
reader.ReadLine();//先讀取一行(如果檔案上方沒有標題之類的東西,可不要這行代碼)
string oneline;
while((oneline =reader.ReadLine()) != null)
{
oneline=oneline.Trim();
if(oneline != "")
{
string [] ss=oneline.Split(",".ToCharArray());//每行的資料以,隔開,儲存在數組裡
if(!existedName(ss[0].ToString())) ss[0]是數組第一個元素,以此判斷資料庫中資料是否存在
{
StringBuilder sb=new StringBuilder();執行個體化StringBuilder
sb.Append("insert into tab_adminuser values(");
for(int i=0;i<ss.Length;i++)
{
sb.Append("'"+ss[i]+"'"+",");
}
sb.Append("'3,'");//以上幾句是構造SQL的插入語句
//sb.Remove(sb.ToString().LastIndexOf(","),1);
sb.Append(")");
//Response.Write(sb.ToString());
//Response.End();
dc.exeSQL(sb.ToString());//執行SQL,DC是我的一個類,作用是完成資料庫插入
}
}
}
reader.Close();//記得要關閉輸入輸出資料流
}
else
{
Response.Write("<script language='javascript'>alert('指定的檔案不存在。');history.go(-1);</script>");
Response.End();
}
}