Storing Image Bytes into database not working - c#

Hello everyone I am making a simple web application that utilizes the users webcam and/or allows you to upload pictures. Please ignore the error in the images, it's done on purpose.
I get the Bytes of the Image like this:
Now I want to enter it into my Database with the SQL data type Image.
In my data access layer I have parameters that look like this:
.
public int AddParam(string ParamName, byte[] pic)
{
return AddParam( ParamName, pic);
}
I entered them and tried to execute it like this:
DataAccessLayer DataAccessLayer = new DataAccessLayer()
DataAccessLayer.PictureCaptured(dlStudentID.SelectedValue.ToString(),imgByte.ToArray());
DataSet ds = new DataSet();
DataAccessLayer .WebExecute(out ds);
It gives me an error like this:
I don't understand why it is doing that.
Please let me know if you have any tips or answers to it.
Thank You very much.

Use this method for converting image into bytes,
public byte[] ImageToByte(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}

If I had to guess, the method AddParams is calling itself over and over and over again which is why you received a StackOverFlowException:
https://msdn.microsoft.com/en-us/library/system.stackoverflowexception(v=vs.110).aspx

Related

System.byte error while reading a pdf file in C#

i have tried every possible solution that is given on website.
private byte[] GetBinaryFile()
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
return bytes;
}
This is what i was trying to Read from the fileuploader which didn't work. Then i changed the idea i uploaded the file on the server first and then i was trying to read but that again gave me the same error of system.byte(). Thing is it does not return the byte format of the pdf but it worked perfectly on my local system does it has anything to do with the server? Any help will be appreciated
you can try this:-
byte[] bytes = new byte[FileUpload1.PostedFile.ContentLength];
bytes = FileUpload1.FileBytes;

How to save a file from database to server

Question is rather simple, and somewhat pointless I understand, but still...
Database is on the server, of course, and I need an action that will when initiated grab that file from database and save it to a folder that is in my AppSettings["Active"] configuration property.
Basically,
public ActionResult Activate(int id)
{
Project project = db.Projects.Find(id);
var activeProjectData = project.XML; // project.XML returns byte[] type
//For download (not in this method of course) i'm using something like return File(activeProjectData, "text/xml"); and that works ok
}
Now I want to save that file to AppSettings["Active"] path. Not to sure how to go about it. I've tried using System.IO.File.Create() but that didn't quite turn out well.
Any help is appreciated.
Simply create a FileStream and use it to write the data:
string fileName = ConfigurationManager.AppSettings["Active"];
using(var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write) )
{
fs.Write(project.XML, 0, project.XML.Length);
}
If you don't need more control than that, there is a simple helper method on the File class:
File.WriteAllBytes(fileName, project.XML);
You'll need to use a FileStream
SqlCommand ("select fileBin from SomeTable", connection);
byte[] buffer = (byte[]) command.ExecuteScalar ();
connection.Close();
FileStream fs = new FileStream(#"C:\filename.pdf", FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
fs.Close();

Convert .db to binary

I'm trying to convert a .db file to binary so I can stream it across a web server. I'm pretty new to C#. I've gotten as far as looking at code snippets online but I'm not really sure if the code below puts me on the right track. How I can write the data once I read it? Does BinaryReader automatically open up and read the entire file so I can then just write it out in binary format?
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream("output.bin", FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
long totalBytes = new System.IO.FileInfo("input.db").Length;
byte[] buffer = null;
BinaryReader binReader = new BinaryReader(File.Open("input.db", FileMode.Open));
}
}
}
}
Edit: Code to stream the database:
[WebGet(UriTemplate = "GetDatabase/{databaseName}")]
public Stream GetDatabase(string databaseName)
{
string fileName = "\\\\computer\\" + databaseName + ".db";
if (File.Exists(fileName))
{
FileStream stream = File.OpenRead(fileName);
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "binary/.bin";
}
return stream;
}
return null;
}
When I call my server, I get nothing back. When I use this same type of method for a content-type of image/.png, it works fine.
All the code you posted will actually do is copy the file input.db to the file output.bin. You could accomplish the same using File.Copy.
BinaryReader will just read in all of the bytes of the file. It is a suitable start to streaming the bytes to an output stream that expects binary data.
Once you have the bytes corresponding to your file, you can write them to the web server's response like this:
using (BinaryReader binReader = new BinaryReader(File.Open("input.db",
FileMode.Open)))
{
byte[] bytes = binReader.ReadBytes(int.MaxValue); // See note below
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
Response.End();
}
Note: The code binReader.ReadBytes(int.MaxValue) is for demonstrating the concept only. Don't use it in production code as loading a large file can quickly lead to an OutOfMemoryException. Instead, you should read in the file in chunks, writing to the response stream in chunks.
See this answer for guidance on how to do that
https://stackoverflow.com/a/8613300/141172

C# Overload Error Message

So I've been trying to use this piece of code below to try and upload an image into the SharePoint image library.
static NetworkCredential credentials = new NetworkCredential(username, password, domain);
static ClientContext clientContext = new ClientContext(siteURL);
static Web site = clientContext.Web;
static List list = site.Lists.GetByTitle("Site Images");
private static byte[] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData;
}
private static void uploadImage()
{
String fileName = "Sunset";
String filePath = "C://Documents and Settings//Desktop//Sample Extracted Pic.jpeg";
list.RootFolder.Files.Add(fileName, StreamFile(filePath));
}
...And everything seems fine (at least within the compiler), until you get to: list.RootFolder.Files.Add(fileName, StreamFile(fileName));
The compiler returns an error saying No overload for method 'Add' takes 2 arguments, and I understand what it's saying, but I have no idea why I am getting that error. Does anyone have any idea or proposed solutions? All feedback is appreciated.
The client object model's Add method only has one parameter: FileCreationInformation. See this MSDN page for more details: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.filecollection.add.aspx

Get Binary data from a SQL Database

I have an ASP .Net (3.5) website. I have the following code that uploads a file as a binary to a SQL Database:
Print("
protected void UploadButton_Click(object sender, EventArgs e)
{
//Get the posted file
Stream fileDataStream = FileUpload.PostedFile.InputStream;
//Get length of file
int fileLength = FileUpload.PostedFile.ContentLength;
//Create a byte array with file length
byte[] fileData = new byte[fileLength];
//Read the stream into the byte array
fileDataStream.Read(fileData, 0, fileLength);
//get the file type
string fileType = FileUpload.PostedFile.ContentType;
//Open Connection
WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN());
//Create New Record
BinaryStore NewFile = new BinaryStore();
NewFile.BinaryID = "1";
NewFile.Type = fileType;
NewFile.BinaryFile = fileData;
//Save Record
db.BinaryStores.InsertOnSubmit(NewFile);
try
{
db.SubmitChanges();
}
catch (Exception)
{
throw;
}
}");
The files that will be uploaded are PDFs, Can you please help me in writing the code to get the PDF out of the SQL database and display it in the browser. (I am able to get the binary file using a linq query but not sure how to process the bytes)
So are you really just after how to serve a byte array in ASP.NET? It sounds like the database part is irrelevant, given that you've said you are able to get the binary file with a LINQ query.
If so, look at HttpResponse.BinaryWrite. You should also set the content type of the response appropriately, e.g. application/pdf.
How big are the files? Huge buffers (i.e. byte[fileLength]) are usually a bad idea.
Personally, I'd look at things like this and this, which show reading/writing data as streams (the second shows pushing the stream as an http response). But updated to use varchar(max) ;-p
protected void Test_Click(object sender, EventArgs e)
{
WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN());
var GetFile = from x in db.BinaryStores
where x.BinaryID == "1"
select x.BinaryFile;
FileStream MyFileStream;
long FileSize;
MyFileStream = new FileStream(GetFile, FileMode.Open);
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)FileSize);
MyFileStream.Close();
Response.Write("<b>File Contents: </b>");
Response.BinaryWrite(Buffer);
}
I tryed this and this did not work. I get a compile error on this line "MyFileStream = new FileStream(GetFile, FileMode.Open);"
I not sure where i am going wrong, is it due to the way i have stored it?
When you store binary files in SQL Server it adds an OLE Header to the binary-data. So you must strip that header before actually reading the byte[] into file. Here's how you do this.
// First Strip-Out the OLE header
const int OleHeaderLength = 78;
int strippedDataLength = datarow["Field"].Length - OleHeaderLength;
byte[] strippedData = new byte[strippedDataLength];
Array.Copy(datarow["Field"], OleHeaderLength,
strippedData , 0, strippedDataLength );
Once you run this code, strippedData will contain the actual file data. You can then use MemoryStream or FileStream to perform I/O on the byte[].

Categories

Resources