Camillia
asked on
Response.AddHeader: I have to save the file, can't open it right there
I 'm using code below to descrypt a file and after it's decrypted, I want to open it. I click on the link to open the file and I get 3 options: save file, open file, download file...
If I click, "open", the file opens but I get a msg that the content cant be open/corrupted.
If I click "save", then go to the folder and open the file..the file is ok and opens just fine.
I dont know why that is. Dont think it's the encryption/decryption that's doing it.
I see the file's name as "whatever.pdf"...so the extension is there. This is the code I have:
The decryption code:
If I click, "open", the file opens but I get a msg that the content cant be open/corrupted.
If I click "save", then go to the folder and open the file..the file is ok and opens just fine.
I dont know why that is. Dont think it's the encryption/decryption that's doing it.
I see the file's name as "whatever.pdf"...so the extension is there. This is the code I have:
Byte[] bytesFile = null;
string fileExt = string.Empty;
string fileName = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
bytesFile = (Byte[])sdr[2];
fileExt = sdr[1].ToString();
fileName = sdr[0].ToString();
}
}
var decryptFile = bytesFile; //GetEncryptedFile(docId.Text);
var decrypted = EncryptData(decryptFile, key, key, false);
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Response.ContentType = sdr[1].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentType = fileExt;
Response.BinaryWrite(decrypted);
Response.Flush();
Response.End();
The decryption code:
private static byte[] EncryptData(byte[] input, byte[] desKey, byte[] desIV, bool encrytp = true)
{
MemoryStream fin = new MemoryStream(input);
MemoryStream fout = new MemoryStream();
int rd = 1024;
byte[] bin = new byte[rd];
long rdlen = 0;
long totlen = fin.Length;
int len;
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = null;
if (encrytp)
{
encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
}
else
{
encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
}
while (rdlen < totlen)
{
len = fin.Read(bin, 0, rd);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
return fout.ToArray();
}
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.