简体   繁体   中英

Sending a file to desktop application (client) from ASP.NET

I am developing licensing for a desktop application. A simple workflow:

  1. User's details are submitted via HttpPost method to server (or other)
  2. Server checks details and generates files.
  3. Server sends a file to user (as a confirmation)

I need help with Step 3- how to send a file to user?

For example, User (HttpPost)

var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("serialNumber", "AAAA"),
    new KeyValuePair<string, string>("email", "test@123"),
    new KeyValuePair<string, string>("HWID", "AAAA-BBBB-CCCC-DDDD"),
};

var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync("https://localhost:44302/testCom.aspx", content).Result;

if (response.IsSuccessStatusCode)
{
    //Code for file receiving?

}

Server

protected void Page_Load(object sender, EventArgs e)
{
            //Check license ID

            //Issue license file - How to?

            //Mark database
}

You can use a Response class to send a file back to client

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();
private void sendFile(string path, string fileName)
{
    FileStream fs = new FileStream(path, FileMode.Open);
    streamFileToUser(fs, fileName);
    fs.Close();
}

private void streamFileToUser(Stream str, string fileName)
{
    byte[] buf = new byte[str.Length];  //declare arraysize
    str.Read(buf, 0, buf.Length);

    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    HttpContext.Current.Response.AddHeader("Content-Length", str.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.OutputStream.Write(buf, 0, buf.Length);
    HttpContext.Current.Response.End();
}

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