0

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.

user979331
  • 11,039
  • 73
  • 223
  • 418
  • Can you expound on "It does not work"? Is there an error message? What are the exact results you get? Also... when you say "so it starts downloading"... Do you mean you want a user to be able to download the file to their client? – Casey Crookston Aug 21 '19 at 14:05
  • also please elaborate asp.net, is it MVC or WebForms and how you return? – Azaz ul Haq Aug 21 '19 at 14:05
  • Possible duplicate of [Returning a file to View/Download in ASP.NET MVC](https://stackoverflow.com/questions/5826649/returning-a-file-to-view-download-in-asp-net-mvc) – Azaz ul Haq Aug 21 '19 at 14:08
  • When I try to convert it to bytes, its returns 0 bytes. – user979331 Aug 21 '19 at 14:16
  • Ok, so it doesn't throw an error. But `fileBytes` ends up being empty. Is that correct? If that's the case, then we'll need more context around how the last line in your OP is called. At that point, does `FilePath` have a value? – Casey Crookston Aug 21 '19 at 14:22
  • (as a side note, and just as an fyi... standard C# naming conventions would dictate that variables start with a lower case. So `FilePath` should really be `filePath`.) – Casey Crookston Aug 21 '19 at 14:23

0 Answers0