Reputation: 2326
I'm trying to write a string to a file that a user can download from my site.
var tcxString = "Some code to get my string";
byte[] bytes;
MemoryStream cvsStream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(cvsStream, tcxString);
cvsStream.Seek(0, SeekOrigin.Begin);
bytes = cvsStream.ToArray();
Response.Clear();
Response.AppendHeader("content-length", cvsStream.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
Response.BinaryWrite(bytes);
The output becomes:
ÿÿÿÿ Some code to get my string
I'm guessing it has to do with my Seek location but I don't know what the correct Seek should be. I see junk at the end of my file sometimes too. How can I get rid of the junk at the beginning and end of my file?
Upvotes: 0
Views: 2461
Reputation: 8214
Is it a text file you are writing? Just write it's content to the output stream using Response.Write.
string tcxString = "Some code to get my string";
Response.Clear();
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
Response.Write(tcxString);
Upvotes: 2
Reputation: 4585
This is because of binary formatter you are using.. try Encoding.GetBytes instead.
var tcxString = "Some code to get my string";
byte[] bytes = Encoding.UTF8.GetBytes(tcxString);
Response.Clear();
Response.AppendHeader("content-length", bytes.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
Response.BinaryWrite(bytes);
Regards
Upvotes: 2