I am trying to figure out how to allow my users to be able to save their outlook files to a sql database using c#/.net. I am using a normal file upload control and what I thought was I could just save it is a string but and put in a link button but that didn't work for me.
This was my idea for the code:
string ImageName1 = string.Empty;
byte[] Image1 = null;
if (Images1.PostedFile != null && Images1.PostedFile.FileName != "")
{
ImageName1 = Path.GetFileName(Images1.FileName);
Image1 = new byte[Images1.PostedFile.ContentLength];
HttpPostedFile UploadedImage = Images1.PostedFile;
Images1.PostedFile.InputStream.Read(Image1, 0, Images1.PostedFile.ContentLength);
UploadedImage.InputStream.Read(Image1, 0, (int)Images1.PostedFile.ContentLength);
}
Any information on how to do that would be helpful!
You can store files as BLOBs in the database.
I don't quite follow your code, normally you call a stored procedure and pass parameters or specify the command as text in c# for communicating with the SQL server.
This link gives an example of how to insert blob into database.
Related
I have some problem. I'am try to save *.docx fail in sql server and show it in web-site. I can save my file in sql server using this code
Byte[] bytes = File.ReadAllBytes(varFilePath);
String file = Convert.ToBase64String(bytes);
using (SqlConnection sql_connetion = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_connection"].ConnectionString))
{
sql_connetion.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO use_of_rule (ID, taj) Values('3', #File)", sql_connetion))
{
sqlWrite.Parameters.Add("#File", bytes);
sqlWrite.ExecuteNonQuery();
return "ok";
}
}
I want to display the content of the file in the web browser. How I can do it?
If you are using Word from WAS (Office Web App Server), you need to do something like this:
1 Create a simple web site to read the data from sql.
You could create a Generic Handler (ashx) in ASP.Net site, providing the plain word file data as response. Dont forget to set the content type as "application/vnd.openxmlformats-officedocument.wordprocessingml.document".
2 Use url encoding to encode the link created in step 1, including all parameters you may want to pass into it.
3 To launch Word, you need to nav it to http(s)://your.was.server.name/op/view.aspx?src=paste.encoded.url.here
I am making a program which requires getting the local directory of an image from a MySQL database table. For the moment, I have made the directory of the image I want to retrieve equal to C:\Users\User\Pictures\PictureName.PNG in the MySQL table. The method I have written up is able to retrieve this data from the database through a Select statement and set the PictureBox image as a new Bitmap with the path retrieved from the Selectstatement.
I couldn't find the information I was looking for online as most of the answers relate to using the BLOB field in MySQL to store images, but my question is if I were to put my database on a server and with the pictures on there too, would my method scale to accommodate for those changes or would I have to add other functionality in order for it to work on a server as well?
Here is my code below:
public void setImage() {
string path = sql.RetrieveImage(SelectQuery.RetrievePicture());
PictureBox1.Image = new Bitmap(path);
}
public string RetrieveImage(Query query) {
string path = "";
// OpenDatabaseConnection() will open up a connection to the database
// through connection and if successful, will return true.
if (this.OpenDatabaseConnection()) {
// query.ToSql() returns a string format of the select statement
// required to retrieve the local image directory
using (MySqlCommand cmd = new MySqlCommand(query.ToSql(), connection)) {
MySqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
path = dataReader[0] + "";
dataReader.Close();
}
this.CloseDatabaseConnection();
}
return path;
}
Storing images in a DB is a bad idea. Storing paths to image files is a much better way to go, IMO.
This SO question has a few links to really good supporting information.
If you must go that route, however, then yes, the BLOB field (or a VarBinary(MAX) in SQLServer) is the way to do it. You can retrieve those images as Byte[] data.
im new to c#, can somone please tell me how to add image to database, from picture box using c#.
i have a registration form which user is added to database(SQL 2008), but i have no idea how to add image of the user to database, which contain many columns of user information and a column of picture.
sql<2008> visual studio <2010>
You should have a binary field in DB for that. Read your image like binary array and save in into DB. But It is not goog practice as for me. I usually save image in cloud or folder and in DB - only URL
create table IMAGELOAD
(img1 binary)
while saving send path of the file to this field
Suggestion :
Instead saving image into database.Save in application folder.
Can you be more specific?
What you don't know how to do?
How to get image from pictureBox? This can help you, hope.
//Save content of imageBytes to db VARBINARY(MAX)
byte[] imageBytes;
using (imgStr = new System.IO.MemoryStream())
{
pictureBox.Image.Save(imgStr, System.Drawing.Imaging.ImageFormat.Jpeg); // Depending on your format.
imageBytes = imgStr.ToArray();
}
//to load from db use
using (Stream imgStr = new MemoryStream(imageBytes))
{
pictureBox.Image = System.Drawing.Image.FromStream(imgStr);
}
how can i save the file using c# into the SQL server dataqbase after user has selected the file location using fileupload control in asp.net .
Please look into this article Save Files to SQL Server Database using FileUpload Control
I would love if you first search on gooogle and than ask for the help if you find out difficult to understand anyways check the following article help you to achieve your task
C# Save and Load Image from Database
You might try something like this:
if (this.fileUploader.PostedFile == null ||
this.fileUploader.PostedFile.ContentLength < 1)
{
this.LabelError.Text = this.GetGlobalResourceObject("Messages", "NoFileToUpload")
.ToString();
return;
}
MyTableWithImageField i = new MyTableWithImageField();
i.ImageData = this.fileUploader.FileBytes;
command.CommandText = #"InsertMyTableWithImageField";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#ImageData", i.ImageData);
You may also want to check this from MSDN: Uploading Files in ASP.NET 2.0
I ask this question as a followup of this question.
A solution that uses bcp and xp_cmdshell, that is not my desired solution, has been posted here.
I am new to c# (since I am a Delphi developer) anyway I was able to create a simple CLR stored procedure by following a tutorial.
My task is to move a file from the client file system to the server file system (the server can be accessed using remote IP, so I cannot use a shared folder as destination, this is why I need a CLR stored procedure).
So I plan to:
store from Delphi the file in a varbinary(max) column of a temporary table
call the CLR stored procedure to create a file at the desired path using the data contained in the varbinary(max) field
Imagine I need to move C:\MyFile.pdf to Z:\MyFile.pdf, where C: is a harddrive on local system and Z: is an harddrive on the server. C is in New York, Z is in London and there is no VPN between them, just https connection.
I provide the code below (not working) that someone can modify to make it work? Here I suppose to have a table called MyTable with two fields: ID (int) and DATA (varbinary(max)). Please note it doesn't make a difference if the table is a real temporary table or just a table where I temporarly store the data. I would appreciate if some exception handling code is there (so that I can manage an "impossible to save file" exception).
I would like to be able to write a new file or overwrite the file if already existing.
[Microsoft.SqlServer.Server.SqlProcedure]
public static void VarbinaryToFile(int TableId)
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command = new SqlCommand("select data from mytable where ID = #TableId", connection);
command.Parameters.AddWithValue("#TableId", TableId);
// This was the sample code I found to run a query
//SqlContext.Pipe.ExecuteAndSend(command);
// instead I need something like this (THIS IS META_SYNTAX!!!):
SqlContext.Pipe.ResultAsStream.SaveToFile('z:\MyFile.pdf');
}
}
(one subquestion is: is this approach correct or there is a way to directly pass the data to the CLR stored procedure so I don't need to use a temp table?)
If the subquestion's answer is No, could you describe the approach of avoiding a temp table? So is there a better way then the one I describe above (=temp table + Stored procedure)? A way to directly pass the dataastream from the client application to the CLR stored procedure? (my files can be any size but also very big)
is [there] a way to directly pass the data to the CLR stored procedure so I don't need to use a temp table?
Yes, it is both possible and rather simple to pass a binary file to a SQLCLR stored procedure and have it write the contents to disk, and not require first placing those contents into a table--temporary or real.
[Microsoft.SqlServer.Server.SqlProcedure]
public static void SaveFileToLocalDisk([SqlFacet(MaxSize = -1)] SqlBytes FileContents,
SqlString DestinationPath)
{
if (FileContents.IsNull || DestinationPath.IsNull)
{
throw new ArgumentException("Seriously?");
}
File.WriteAllBytes(DestinationPath.Value, FileContents.Buffer);
return;
}
Or, since you said that the files are sometimes large, the following should be much easier on memory usage as it makes use of the streaming functionality:
[Microsoft.SqlServer.Server.SqlProcedure]
public static void SaveFileToLocalDiskStreamed(
[SqlFacet(MaxSize = -1)] SqlBytes FileContents, SqlString DestinationPath)
{
if (FileContents.IsNull || DestinationPath.IsNull)
{
throw new ArgumentException("Seriously?");
}
int _ChunkSize = 1024;
byte[] _Buffer = new byte[_ChunkSize];
using (FileStream _File = new FileStream(DestinationPath.Value, FileMode.Create))
{
long _Position = 0;
long _BytesRead = 0;
while (true)
{
_BytesRead = FileContents.Read(_Position, _Buffer, 0, _ChunkSize);
_File.Write(_Buffer, 0, (int)_BytesRead);
_Position += _ChunkSize;
if (_BytesRead < _ChunkSize || (_Position >= FileContents.Length))
{
break;
}
}
_File.Close();
}
return;
}
The assembly containing this code will, of course, need to have a PERMISSION_SET of EXTERNAL_ACCESS.
In both cases, you would execute them in the following manner:
EXEC dbo.SaveFileToLocalDiskStreamed 0x2A20202A, N'C:\TEMP\SaveToDiskTest.txt';
And "0x2A20202A" should give you a file containing the following 4 characters (asterisk, space, space, asterisk):
* *
See http://www.mssqltips.com/tip.asp?tip=1662
Why are you putting these files into database? If you have http/https connection you can upload the file to the server, write into a protected dierctory and create a page to list those files and give a link to download it. If you want to store some extra information you can write it into database. You just need to change the name of file at server side (use a unique name).
After some research I conclude that it makes no sense, it is better to drop the support of 2005 and use 2008 fielstream feature. I can have a conditional logic to choose between 2005 and 2008 and use filestream only for 2005.