日期:2014-05-17  浏览次数:20954 次

如何用ASP.net中的FileUpload将txt内容写入数据库?
如题。小弟菜鸟。现有一个txt文件,其中有N行string数据,
比如:
aaaaaaa
bbbbbbb
ccccccc
ddddddd

想通过Upload控件将每一行传入SQL数据库中的一个表中。
请问如何实现?求代码!

------解决方案--------------------
以下代码直接拷贝执行,。
数据库、表自己创建。
HTML code
<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void btnUpload_Click( object sender, EventArgs e )
  {
    if (FileUpload1.PostedFile.InputStream.Length < 1)
    {
      Msg.Text = "请选择文件。";
      return;
    }
    string FileName = FileUpload1.FileName;
    if (FileName.ToLower().IndexOf(".txt") == -1)
    {
      Msg.Text = "请选择文本文件。";
      return;
    }
    int FileLen = FileUpload1.PostedFile.ContentLength;
    byte[] input = new byte[FileLen];
    System.IO.Stream UpLoadStream = FileUpload1.PostedFile.InputStream;
    UpLoadStream.Read(input, 0, FileLen);
    UpLoadStream.Position = 0;
    System.IO.StreamReader sr = new System.IO.StreamReader(UpLoadStream, System.Text.Encoding.Default);
    String content = sr.ReadToEnd();
    sr.Close();
    UpLoadStream.Close();
    UpLoadStream = null;
    sr = null;

    String sql = "Inser INTO Table(name,Title) Values(@name,@Title) ";
    System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection("你的数据库连接字符串");
    cn.Open();
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql,cn);
    String[] d = System.Text.RegularExpressions.Regex.Split(content, "\r\n");
    for (int i = 0; i < d.Length; i++)
    {
      if (d[i].Trim() != "")
      {
        //Response.Write("<li>" + d[i]);
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@name", d[i]);
        cmd.Parameters.AddWithValue("@name", d[i]);
        cmd.ExecuteNonQuery();
      }
    }    
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>不经保存,直接读取上传文件的内容</title>
</head>
<body>
  <form id="MengXianhui" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click"></asp:Button>
    <p>
      <asp:Label ID="Msg" runat="server" ForeColor="Red"></asp:Label></p>
  </form>
</body>
</html>