如何使用对话框下载?

时间:2011-09-22 06:04:56

标签: c# asp.net download

 SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
        SqlCommand Command = connection.CreateCommand();

        SqlDataReader SQLRD;

        Command.CommandText = "Select * from Attendance";

        connection.Open();
        SQLRD = Command.ExecuteReader();


        string data = "";



        while (SQLRD.Read())
        {
            data += SQLRD[0].ToString() + ",";
            data += SQLRD[1].ToString() + ",";
            data += SQLRD[2].ToString() + ",";
            data += SQLRD[3].ToString() + ",";
            data += SQLRD[4].ToString() + ",";
            data += SQLRD[5].ToString() + ",";
            data += SQLRD[6].ToString() + ",";
            data += SQLRD[7].ToString();
            data += "\n";

        }

        SQLRD.Close();
        connection.Close();

        string filename = @"C:\download.csv";
        FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine(data);
        sw.Flush();
        sw.Close();
        fs.Close();

目前我的代码没有显示用户指定文件位置的对话框。始终存储在@“C:\ download.csv”中是“硬编码”的。替换这个我想使用一个对话框。

1 个答案:

答案 0 :(得分:2)

首先,我要说不要将 System.String对象用于contact字符串。始终使用System.Text.StringBuilder对象。

System.Text.StringBuilder sb = new System.Text.StringBuilder();
 while (SQLRD.Read())
  {
  sb.Append(String.Format("{0},{1},{2},{3},{4},{5},{6},{7}\n",
      SQLRD[0],SQLRD[1],SQLRD[2],SQLRD[3],SQLRD[4],SQLRD[5],SQLRD[6],SQLRD[7]));
   }

要下载数据,

byte[] ar = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/octet-stream");
Response.AddHeader("Content-Length", ar.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv");
Response.BinaryWrite(ar);
Response.Flush();
Response.End();