In my C# winform app. I connected my program to the MS SQL Server 2005 successfully, now I want to add a new column of type Image, how can I Insert the Image in the DB and get it back? and in our Business Logic Class which data type variable we will declare?
how can I Insert the Image in the DB and get it back?
you need to get the image in bytes as shown in below code
Edited Code Example
private void BrowseImage(object o)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// Set filter for file extension and default file extension
//openFileDialog.DefaultExt = ".bmp";
//openFileDialog.Filter = "24-Bit Bitmap (.bmp)|*.bmp";
openFileDialog.InitialDirectory = #"C://"
openFileDialog.DefaultExt = ".jpg";
openFileDialog.Filter =
"BMP (*.BMP)|*.BMP|" +
"JPEG (*.JPG; *.JPEG; *.JPE)|*.JPG;*JPEG|" +
"GIF (*.GIF)|*.GIF|" +
"TIFF (*.TIFF)|*.TIFF|" +
"PNG (*.PNG)|*.PNG|" +
"DIB (*.DIB)|*.DIB|" +
"JFIF (*.JFIF)|*.JFIF";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openFileDialog.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = openFileDialog.FileName;
Stream stream = openFileDialog.OpenFile();
byte[] bytes = null;
if (stream != null && stream.CanRead)
{
bytes = new byte[stream.Length];
stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
stream.Close();
}
}
}
in our Business Logic Class which data type variable we will declare?
you need to define the image property as Byte[] and assign this property with the bytes[] got above.
Related
I have successfully converted image to binary and saved it into the database using linq to sql WPF and now i want to retrieve it back to image format and save it to a specific folder in computer.
i have read many blogs and articles which retrieves the image binary from database and then shows it into the PictureBox, what i want to do is to select the image and save it to a specific folder using linq to sql.
code which i have tried so far for uploading an image:
private void Browse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".jpg";
ofd.Filter = "Image File (.jpg) | *.jpg";
Nullable<bool> result = ofd.ShowDialog();
if(result == true)
{
string fileName = ofd.FileName;
_txtFileName.Text = fileName;
}
}
private void Upload_Click(object sender, RoutedEventArgs e)
{
using(ImageDataContext db=new ImageDataContext())
{
image_data img = new image_data();
img.image = ConverImageToBinary(_txtFileName.Text);
try
{
db.image_datas.InsertOnSubmit(img);
db.SubmitChanges();
MessageBox.Show("Picture Upload Successfully", "Success", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public static byte[] ConverImageToBinary(string convertedImage)
{
try
{
FileStream fs = new FileStream(convertedImage, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return image;
}
catch(Exception ex)
{
throw ex;//MessageBox.Show(ex.Message, "error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
First of your code to read the image is way to complex, you're opening it as a Stream and reading well, all bytes. There's a method that does exactly that so you can replace your whole ConverImageToBinary method with
img.image = File.ReadAllBytes(_txtFileName.Text);
Also you never "converted" anything to anything, an image is just an array of bytes on disk, you've read it, saved it to the database, if you read it back and save it back (using this time File.WriteAllBytes) it will work just fine, so
IF you want to write to the disk then just save the image back to disk as such:
File.WriteAllBytes(#"d:\myfile.bmp",img.Image.ToArray()) ;
And make sure you change the extention to match your file type (so bmp for a bitmap jpg for a jpeg etc)
Actually, I have saved a file in BinaryData in Sql and now I am able to download that file by converting the BinaryData into Bytes.
My code is :
object value = (sender as DevExpress.Web.ASPxGridView.ASPxGridView).GetRowValues(e.VisibleIndex, "ID");
Int64 FileID = Convert.ToInt64(value);
var filedata = (from xx in VDC.SURVEY_QUESTION_REPLIES
where xx.ID == FileID
select xx).FirstOrDefault();
string fileextension = filedata.FILE_EXTENSION.ToString();
string fileName = filedata.ANSWER_TEXT.ToString() + fileextension;
string DocumentName = null;
FileStream FStream = null;
BinaryWriter BWriter = null;
byte[] Binary = null;
const int ChunkSize = 100;
int SizeToWrite = 0;
MemoryStream MStream = null;
DocumentName = fileName;
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
BWriter = new BinaryWriter(FStream);
Binary = (filedata.FILE_DATA) as byte[];
SizeToWrite = ChunkSize;
MStream = new MemoryStream(Binary);
for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
{
if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i;
byte[] Chunk = new byte[SizeToWrite];
MStream.Read(Chunk, 0, SizeToWrite);
BWriter.Write(Chunk);
BWriter.Flush();
}
BWriter.Close();
FStream.Close();
FStream.Dispose();
System.Diagnostics.Process.Start(#"c:\" + DocumentName);
and it is directly saving the file to the location C Drive.
Now,My Requirement is that,I need to get a Prompt for saving that file and user need to select the location of saving.
Is that Possible ?
You create a filestream with a fixed location here:
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
What you would have to do is something like this:
var dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
FStream = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
// put the rest of your file saving code here
}
Remember to import the Forms namespace
using System.Windows.Forms;
If its Forms app You can use SaveFileDialog class
it is possible,
you can use a saveFileDialog that you create in your designer and call the "show" method to open that dialog :
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
Source : http://msdn.microsoft.com/en-gb/library/system.windows.forms.savefiledialog.aspx
I see that you use web components of DevExpress, so assuming that you want to send the stream to response for the client to save the file.
If it is an ASP.NET MVC application, you can return FileContentResult as action result directly. Otherwise, you might use the following sample adapting into your code
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DocumentName);
MStream.WriteTo(Response.OutputStream);
Depending on user's browser settings, save file dialog might be shown to the user.
I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.
I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. Here is my
handler code:
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string fileType = file.ContentType;
string strFileName = fileName;
FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] imagebytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
DBAccess dbacc = new DBAccess();
dbacc.saveImage(imagebytes);
string msg = "{";
msg += string.Format("error:'{0}',\n", string.Empty);
msg += string.Format("msg:'{0}'\n", strFileName);
msg += "}";
context.Response.Write(msg);
}
I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. I can assure you that the image is being saved to the temp folder. The problem is with the line with (*) the file path is wrong. This is the file path that is being retrieved. "'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.". The temp folder is located locally inside my project and I want to retrieved the image within that folder. How can I set the file path to my desired location? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call?
Credits to these articles:
Save and Retrieve Files from SQL Server Database using ASP.NET
Async file upload with jQuery and ASP.NET
Just these 3 lines will do:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );
using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}
I want to read the content of the file opened using file dialog box and then save it in a byte array to pass it to a web service
Stream myStream;
OpenFileDialog saveFileDialog1 = new OpenFileDialog();
saveFileDialog1.Filter = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
NSITESERVICE.UploadSoapClient obj = new NSITESERVICE.UploadSoapClient();
byte[] filebytes = //what should i pass it over here...
obj.UploadFile("kamal", "p#ssword", filebytes);
// Code to write the stream goes here.
myStream.Close();
}
}
I dont know where i am wrong
Any help is appreciated. Thnaks
You are not assigning anything to filebytes variable so you are essentially passing null to the service. Use File.ReadAllBytes method to read all the bytes and pass it to the webservice.
You're not actually reading the bytes out of the myStream.
byte[] fileBytes = new byte[myStream.Length];
myStream.Read(fileBytes,0,mystream.Length);
obj.UploadFile(...)