I have created a txt file in ASP.NET
string FilePath = HttpContext.Current.Server.MapPath("~/FILENAME.txt");
string FileContent = "";
FileContent += "Text Here" + Environment.NewLine;
File.WriteAllText(FilePath, FileContent);
The file get created, now I am trying to do is return this file in a method so it starts downloading.
I have done some reading and it appears first I have to convert it to bytes and when I try this:
byte[] fileBytes = System.IO.File.ReadAllBytes(FilePath);
It does not work :( What am I doing wrong?
UPDATE
I got this now:
string FilePath = HttpContext.Current.Server.MapPath("~/FILENAME.txt");
string FileContent = "";
FileContent += "Text Here" + Environment.NewLine;
File.WriteAllText(FilePath, FileContent);
var file = HttpContext.Current.Server.MapPath("~/FILENAME.txt");
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=NewFile.txt");
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.TransmitFile(file);
HttpContext.Current.Response.End();
this code is inside a void method and here is my jquery ajax call:
$.ajax({
url: "/api/WebService/spPOImportGenImportPOTxt/" + $("#ID").val(),
type: "POST",
contentType: "application/octet-stream; charset=utf-8",
error: function(request, status, error) {
alert("Something went wrong: " + error);
$.unblockUI();
},
success: function(data) {
alert("Data has been successfully saved.");
console.log(data);
$.unblockUI();
}
});
I am getting the success alert, but the file is not downloading, when I console.log data it returns the text inside the txt file.