Unable to get the Content of the text file saved in the Database(My-Sql) - asp.net

In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell

if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.

Related

Unable to cast object of type 'system.string' to type 'system.Byte[]' when trying to download a file from database

I am trying to download a file from database but its giving me an error called Unable to cast object of type 'System.String' to type 'System.Byte[]' on the line : Response.AddHeader("Content-Length", bytes.ToString());
Please tell me how can I cast string to byte in my case, thank you in advance.
I have a column named SaleFileName from which I want to download a file.
Aspx code:
<asp:TemplateField HeaderText="RecieptName" SortExpression="RecieptName">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Bind("SaleName") %>' Text='<%# Bind("SaleName") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind File:
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
// make sure fileName contains only file name like 'test.pdf'
string FileName = Convert.ToString(e.CommandArgument);
// make sure filePath contains file path like 'Uploads/Scheme/test.pdf'
string FilePath = e.CommandArgument.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
// SqlConnection con = new SqlConnection(connectionString);
// byte[] bytes;
//string ContentType;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "selectSaleFileName from Contributions where SaleFileName = #SaleFileName";
cmd.Parameters.AddWithValue("#SaleFileName", FileName);
//d.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
using ( SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["SaleFileName"];
//byte data = System.Text.Encoding.Unicode.GetBytes(SaleFileName.ToString);
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
// Read the original file from disk
FileStream myFileStream = new FileStream( FilePath ,FileMode.Open);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[Convert.ToInt32(FileSize)];
myFileStream.Read(Buffer, 0, Convert.ToInt32(FileSize));
myFileStream.Close();
// // Tell the browse stuff about the file
Response.AddHeader("Content-Length", bytes.ToString());
// Response.AddHeader("Content-Length", FileNam
//Response.AddHeader("Content-Disposition", "inline; filename=" & fileName.Replace(" ", "_"));
Response.AddHeader("Content-Disposition", "attachment; FileName=" + FileName + ";");
Response.TransmitFile(FileName);
Response.ContentType = "application/octet-stream";
// Send the data to the browser
Response.BinaryWrite(Buffer);
Response.End();
}
}
You can't cast byte[] to string (unless its textual data and you should encode the data using any encoding like unicode, ASCII)
anyway, the problem in the Content-Length on http header, it should be the length of the file
so replace this line:
Response.AddHeader("Content-Length", bytes.ToString());
with this:
Response.AddHeader("Content-Length", FileSize.ToString());
if the file is stored databaase you need to get it as byte array, the following code will help you:
private byte[] ReadFileFromDatabase(string FileName) {
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
byte[] bytes = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "selectSaleFileName from Contributions where SaleFileName = #SaleFileName";
cmd.Parameters.AddWithValue("#SaleFileName", FileName);
cmd.Connection = con;
con.Open();
using ( SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read() )
bytes = (byte[])sdr["SaleFileName"];
}
con.Close();
}
}
return bytes;
}
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
string FileName = Convert.ToString(e.CommandArgument);
byte[] bytes = ReadFileFromDatabase(FileName);
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; FileName=" + FileName + ";");
Response.BinaryWrite(bytes)
Response.End()
}
}
if your file is stored outside database:
public static void DownloadFile(string path, string contentType)
{
FileInfo file = new FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Type", contentType);
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
}
call it as:
string fullPath = Server.MapPath(relativePath);
DownloadFile(fullPath , "application/octet-stream");

File Encryption in mvc5

var graphids = from o in db.OfflineCarts
join i in db.Graphs on o.ItemId equals i.ItemUserID
select i;
GridView gv = new GridView();
gv.DataSource = graphids.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=GraphTable.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Encryption();
public void Encryption()
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = "/Users/Neeraj/Downloads/UserFilesEncrypt.xls";
FileStream fsCrypt = new FileStream(cryptFile, FileMode.CreateNew);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream rs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Read);
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
string inputFile = "/Users/Neeraj/Downloads/GraphTable.xls";
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
I am encrypting the file just instantaneously after it is downloaded by grid view in mvc5 but i am getting 0 byte encrypted file and when i am re downloading the file than i am getting proper encrypted file Can Anybody tell me what is wrong with the code or i have to delay encryption function after download for sometime
use System.Security
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);

BinaryReader.ReadBytes returning junk when converted to string

if I try to explain why I need to do what I'm trying to do it will take a long time, but basically it's this: I have FileUpload control for the user to choose a Jpeg file, I make the upload and after it I want to convert that file to bytes and use it as the source of an Image control.
My code is this one:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The byte array is looking ok, but when I convert it to string it's full of unrecognized characters, I have another page where I do the same thing but instead of getting the bytes from the file I get it from a MySql database and using the same System.Text.Encoding.UTF8.GetString and it works withou a problem.
UPDATE
As asked, this is the code I use when retrieving the from the MySql database:
DataView dv = (DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty);
byte[] buffer = (byte[])dv.Table.Rows[0]["BIN_FOTO"];
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The select of this SqlDataSource3 is a simple Select BIN_FOTO from temp_image. I store this value in the database from a webcam capture WPF program, the code I use to convert the image the webcam captured is:
private string ImageToBase64String(System.Drawing.Image imageData, ImageFormat format)
{
string base64;
MemoryStream memory = new MemoryStream();
imageData.Save(memory, format);
base64 = System.Convert.ToBase64String(memory.ToArray());
memory.Close();
memory.Dispose();
return base64;
}
Then I save the base64 variable to the database.
Hope this clarifies my problem
So you want to read the image file and convert to base 64. After your reading code, do this:
string valor = Convert.ToBase64String(buffer);
Your original code was flawed because you're saving the image, as bytes, to the file with this line of code:
fileUpload1.SaveAs(fileName);
That's not saved as base64, so you have to convert it to base 64 after you read it. Your MySql reading worked because the data was converted to base64 before being saved.
By the way, there's no need for the BinaryReader in this code:
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
You can write this instead:
byte[] buffer;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)
{
long byteLength = fs.Length;
buffer = new byte[byteLength];
int bytesRead = fs.Read(buffer, 0, byteLength);
// optional error check to see that you got all the bytes
if (bytesRead != byteLength)
{
// handle error
}
}
string valor = Convert.ToBase64String(buffer);
I've found the problem, looking at the WPF code I used to convert the image to a Base64String. I just created the same function ImageToBase64String and now it works:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.Drawing.Image teste = System.Drawing.Image.FromFile(fileName);
string valor = ImageToBase64String(teste, System.Drawing.Imaging.ImageFormat.Jpeg);
//System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//long byteLength = new System.IO.FileInfo(fileName).Length;
//byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
//buffer = File.ReadAllBytes(fileName);
//fs.Close();
//fs.Dispose();
//string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
But I still don't know what was wrong with my previous code, anyone can clarify?
This solution worked for me:
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//Add this--------------------
fs.Seek(0, SeekOrigin.Begin);
//----------------------------
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
Just add highlighted line.

Converting issue Byte to Byte

i never work with Bytes before i have a getting error here in may code please have a look
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
SqlDataReader dr = ExecuteReader(Globals.con, CommandType.Text,
"select FileName,MediaData,Extension from media where Id=" + ID);
string FileName="";
Byte[] MediaData= null;
string Extension = "";
while (dr.Read())
{
FileName = dr["FileName"].ToString();
MediaData = Convert.ToByte(dr["MediaData"].ToString()); error is here
Extension = dr["Extension"].ToString();
}
dr.Close();
string filename = (String)FileName;
byte[] fileToDownload = (byte[])MediaData;
String fileExtension = (String)Extension;
in gridview i use this code below it working i need manual date
not like code below
string filename = (String)reader.GetValue(1);
byte[] fileToDownload = (byte[])reader.GetValue(2);
String fileExtension = (String)reader.GetValue(3);
please help me out in it
Convert.ToByte returns a single byte, not an array.
You are also using ToString which can completely convert the binary data into a representation that you can't use:
MediaData = Convert.ToByte(dr["MediaData"].ToString())
Should be:
MediaData = (byte[])dr.Items["MediaData"];

File Upload with HttpWebRequest doesn't post the file

Here is my code to post the file. I use asp fileupload control to get the file stream.
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
requestToSender.KeepAlive = true;
requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength;
BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream);
byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength);
Stream requestStream = requestToSender.GetRequestStream();
requestStream.Write(binData, 0, binData.Length);
requestStream.Close();
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
XMLString.Text = fromSender;
In the page load of CrossPage.aspx i have the following code
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
string strxml = "sample";
Response.Clear();
Response.Write(strxml);
I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?
multipart/form-data doesn't consist of simply writing the file bytes to the request stream. You need to respect the RFC 1867. You may take a look at this post of how this could be done with multiple files.

Resources