Save a file to SQL database using Silverlight and LINQ - c#

What is the best way to save a file to my SQL database using Silverlight and LINQ?
I have read through some articles, some of them here on StackOverflow and there is so much information that I am not sure what is the best.
I have something that works using:
// Read the file
var reader = new StreamReader(openFileDialog.File.OpenRead());
contents = reader.ReadToEnd();
reader.Close();
// Convert to byte[]
byte[] inputbuffer;
var encoding = new UTF8Encoding();
inputBuffer = encoding.GetBytes(contents);
but according to something I read here on StackOverflow, using UTF8Encoding is not a good idea.
Also I can get the file from the database using LINQ when I need it, but how do I convert it back from the byte[] to the actual file?
Or would using WCF to save and retrieve a file be better?
Any ideas are greatly appreciated.

yes UTF8Encoding is not a good option.
You can use the FileStream's copyto method to copy the files bytes into a memorystream and use it's ToArray method to get all bytes instead.
If you can access the DB directly from Silverlight than this should be ok but the second part of your questions indicates that you might not be sure(?) - if so please put this into another question.
Here is a snippet to return the bytes from the file:
var stream = openFileDialog.File.OpenRead();
using (var memStream = new System.IO.MemoryStream())
{
stream.CopyTo(memStream);
return memStream.ToArray();
}
To save it back you will have to use the SaveFileDialog class in silverlight

Related

Read excel, search for and replace pieces of text in web C# application

I have an excel file, need access, replace parts of the text and download the changed file.
But I can not save the changes, I should always keep the version on the server.
I did several searches, but I can only change the file and save the changes.
I tried to solve with the link below, I managed to search and change the file, but I do not know how to download and stop saving the changes.
Find and replace text in Excel using C#
Thank you very much
Read the file into a memory stream. Do your changes and write it to a byte array. Use the byte array bytesInstream to download and the original file remains unaltered.
byte[] byteArray = File.ReadAllBytes("excelFile.xlsx");
using (MemoryStream ms = new MemoryStream())
{
ms.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(ms, true))
{
// Do work here
}
// Convert it to byte array
byte[] bytesInStream = ms.ToArray();
}
I have assumed you are using openxml to make your changes.

String to zip file

I use a webservice that returns a zip file, as a string, and not bytes as I expected. I tried to write it to the disk, but when I open it, it tells me that it is corrupt. What am I doing wrong?
string cCsv = oResponse.fileCSV;//this is the result from webservice
MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(cCsv));
using (FileStream file = new FileStream("test.zip", FileMode.Create, FileAccess.Write))
{
ms.WriteTo(file);
}
ms.Close();
I'm not sure what kind of encoding the string is in, but assuming UTF-8, the following should work. UTF-16 would be another guess.
string cCsv = oResponse.fileCSV;
using (BinaryWriter bw = new BinaryWriter(File.Create("test.zip")))
{
bw.Write(System.Text.Encoding.UTF8.GetBytes(cCsv));
}
It'd be informative to look at the characters and the raw string itself being returned.
Edit
Per Frank's answer, the correct encoding is base64, which of course makes sense because it's binary data stored as a string.
Also, per Frank's answer, if the only action is to directly write a single byte array, then File.WriteAllBytes is more compact.
Ok, i solve the problem:
File.WriteAllBytes("testbase64.zip", Convert.FromBase64String(cCsv));

asp.net core 1.0 mvc. Get raw content from Request.Body

I am trying to get the raw content of Request.Body in asp.net core 1.0 and I was wondering what the proper way of getting the entire body as a byte[] is. If you have any experience with similar situation and know the “proper” way of doing it, please share.
Request.Body is a Stream. The stream has the Read method that takes a buffer which is a byte array you can read the data into. Since you may not know the size of the stream and even not all the content can be available you need to do this in the loop until you read all the data from the stream - this stackoverflow answer shows how to do that (if you don't want to block your thread could use ReadAsync). Alternatively - if you would like to read content to a String you could use the StreamReader class.
I used this code...
using (var requestBodyStream = new MemoryStream())
{
var body = request.Body;
await request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);
requestPayload.Body = await new StreamReader(requestBodyStream).ReadToEndAsync();
}

How to convert byte array to image file?

I have browsed and uploaded a png/jpg file in my MVC web app.
I have stored this file as byte[] in my database.
Now I want to read and convert the byte[] to original file.
How can i achieve this?
Create a MemoryStream passing the array in the constructor.
Read the image from the stream using Image.FromStream.
Call theImg.Save("theimage.jpg", ImageFormat.Jpeg).
Remember to reference System.Drawing.Imaging and use a using block for the stream.
Create a memory stream from the byte[] array in your database and then use Image.FromStream.
byte[] image = GetImageFromDatabase();
MemoryStream ms = new MemoryStream(image);
Image i = Image.FromStream(ms);
May you have trouble with the mentioned solutions on DotNet Core 3.0 or higher
so my solution is:
using(var ms = new MemoryStream(yourByteArray)) {
using(var fs = new FileStream("savePath", FileMode.Create)) {
ms.WriteTo(fs);
}
}
Or just use this:
System.IO.File.WriteAllBytes(string path, byte[] bytes)
File.WriteAllBytes(String, Byte[]) Method (System.IO) | Microsoft Docs

How to save file in SQL Server database if have file path?

I am building some C# desktop application and I need to save file into database. I have come up with some file chooser which give me correct path of the file. Now I have question how to save that file into database by using its path.
It really depends on the type and size of the file. If it's a text file, then you could use File.ReadAllText() to get a string that you can save in your database.
If it's not a text file, then you could use File.ReadAllBytes() to get the file's binary data, and then save that to your database.
Be careful though, databases are not a great way to store heavy files (you'll run into some performance issues).
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
int numBytes = new FileInfo(fileName).Length;
byte[] buff = br.ReadBytes(numBytes);
Then you upload it to the DB like anything else, I'm assume you are using a varbinary column (BLOB)
So filestream would be it but since you're using SQL 2K5 you will have to do it the read into memory way; which consumes alot of resources.
First of the column type varchar(max) is your friend this give you ~2Gb of data to play with, which is pretty big for most uses.
Next read the data into a byte array and convert it to a Base64String
FileInfo _fileInfo = new FileInfo(openFileDialog1.FileName);
if (_fileInfo.Length < 2147483647) //2147483647 - is the max size of the data 1.9gb
{
byte[] _fileData = new byte[_fileInfo.Length];
_fileInfo.OpenRead().Read(_fileData, 0, (int)_fileInfo.Length);
string _data = Convert.ToBase64String(_fileData);
}
else
{
MessageBox.Show("File is too large for database.");
}
And reverse the process to recover
byte[] _fileData = Convert.FromBase64String(_data);
You'll want to dispose of those strings as quickly as possible by setting them to string.empty as soon as you have finished using them!
But if you can, just upgrade to 2008 and use FILESTREAM.
If you're using SQL Server 2008, you could use FILESTREAM (getting started guide here). An example of using this functionality from C# is here.
You would need the file into a byte array then store this as a blob field in the database possible with the name you wanted to give the file and the file type.
You could just reverse the process for putting the file out again.

Categories

Resources