"Write" and "download" a file are mutually exclusive. It's a client part which downloads something. What I can see from your code is different: in response to client's HTTP request, your server side writes and creates temporary file, then this file is sent in HTTP request to the client which downloads it.
In principle, this code should work — almost, but it's full of some absurdities. There is no such content types. You probably mean "text/plain". The
real problem is:
you don't dispose StreamWriter
, so you do not guarantee that your file is saved; it's the best to use
using
statement (don't mix up with
using
clause!). Getting
FullName
is redundant.
First of all, as this is nothing more than a simple text file which could be transferred in ASCII encoding, so you don't even need a file. You could write directly in your response:
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=some-file.txt");
Response.ContentType = "text/plain";
Response.Write();
Response.Write();
Response.Write("\t" + "\t" + "\t\t\Binderab City");
Response.End();
This way, a client side can always download some file, which is not physically a file on the server side.
You can write a file, of course, but it makes sense if you want to write something more complex. As a bonus, I'll demonstrate sending a file with UTF-8 encoding with BOM, so you could use non-ASCII Unicode code points and read the downloaded text file with any Unicode-enabled text editor with standard behavior — recognition of encoding by BOM:
Response.ContentEncoding = System.Text.Encoding.UTF8;
string fileName = string.Format("{0}{1}", System.IO.Path.GetTempPath(), "Activity.txt");
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName, false, Response.ContentEncoding)) {
writer.WriteLine();
writer.WriteLine("...");
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=some-file.txt");
Response.ContentType = "text/plain";
Response.Charset = "utf-8";
Response.WriteFile(fileName);
Response.End();
System.IO.File.Delete(fileName);
See also:
http://en.wikipedia.org/wiki/Byte_order_mark[
^],
http://unicode.org/faq/utf_bom.html[
^],
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[
^].
—SA