简体   繁体   中英

How to save the data in a Client machine directory from SQL Server database of a .net application?

I have written the following C# code using console application to fetch the data from database and save it in a .CSV file.

My question is: here I am saving to an EXCEL file which already exists on my local machine. But I wish that the code should create a file in one of the client machine directories and save the data. How to change this code accordingly?

I use this code in asp.net application for BUTTON_Click EVENT. Do I need to add any namespaces at that point of time?!!

class Program
{
    static void Main(string[] args)
    {
        string strConn = "Data Source=ARYAANCLASS;Initial Catalog=Master;Integrated Security=True";

        SqlConnection conn = new SqlConnection(strConn);

        SqlDataAdapter da = new SqlDataAdapter("select * from QuickBook", conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "QuickBooks");

        DataTable dt = ds.Tables["QuickBooks"];

        StreamWriter sw = new StreamWriter(@"d:\Rudresh\QuickBookData.csv", false);

        int iColCount = dt.Columns.Count;

        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);

            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }

        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }

                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }

            sw.Write(sw.NewLine);
        }

        sw.Close();
    }
}

I don't think you understand what client/server-sides means..

The program you have written is a client program, so if a user opens the executable on his Computer it should work(more or less there are some improvements like: testing if the write folder exists else create it).

Also he must be able to connect to the database so a "try catch"-block around the sql connection is not a bad plan.

If you are trying to create a webpage, it is a total different story. It is not possible to "save" the file to a client location. Then you have to save it on your server in the folder accessible for a web user like in the www/savedcsv folder. Then when the stream is finished, redirect the "web user" to folder www.mydomain.com/savedcsv/newfile.csv and he will be able to download it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM