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();
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.