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();
Related
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
I am a Jr. Programmer trying to get mp4 videos from an API and save them to a folder on the network. I am using the following code;
public static void saveVideos(HttpContent content, String filename, bool overwrite)
{
string pathName = Path.GetFullPath(filename);
using (FileStream fs = new FileStream(pathName, FileMode.Create, FileAccess.Write, FileShare.None))
{
if (fs.CanWrite)
{
byte[] buffer = Encoding.UTF8.GetBytes(content.ToString());
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
fs.Close();
}
}
}
The code will compile without errors but all videos are written to the folder with a size of 1KB. I can't seem to figure out why I am not getting all of the file.
When I inspect the value of the content I see I am getting data that looks like this:
Headers = {Content-Length: 240634544
Content-Disposition: attachment; filename=Orders.dat
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Can anyone point out my error here?
Thanks
This doesn't do what you think it does:
content.ToString()
Unless otherwise overridden, the default implementation of .ToString() simply prints the name of the class. So all you're saving is a bunch of files with class names in them.
What you're probably looking for is the .ReadAsStringAsync() method instead. Or, since you're converting it to bytes anyway, .ReadAsByteArrayAsync() would also work. Perhaps something like this:
byte[] buffer = await content.ReadAsByteArrayAsync();
Of course, since this uses await then your method would have to be async:
public static async Task saveVideos(HttpContent content, String filename, bool overwrite)
If you can't make use of async and await (if you're on an older .NET version), then there are other ways to handle it as well.
Edit: Based on the comments and some of the context of the question, you may be dealing with large files here. In that case, using streams would perform a lot better. I don't have any sample code at the moment, but essentially what you'd want to do is move data directly from one stream to another rather than storing it in an in-memory variable.
If anyone else is having an issue or learning how to save a file using a FileStream hear is the code I used to solve the problem.
public static void saveVideos(HttpContent content, String filename, bool overwrite)
{
string pathName = Path.GetFullPath(filename);
using (Stream fs = new FileStream(pathName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.None))
{
byte[] buffer = content.ReadAsByteArrayAsync().Result;
fs.Write(buffer, 0, buffer.Length);
}
}
Does any one know how to use the package.Saveas function?
package.SaveAs(tempFolderPathAlt + saveas + ".xlsx");
At the moment this is underlined in red with the following error:
The best overloaded method match for
'OfficeOpenXml.ExcelPackage.SaveAs(System.IO.Stream)' has some invalid
arguments
At the moment i'm saving the file in the following way.
FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xls", FileMode.Create);
byte[] byData = package.GetAsByteArray();
aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(byData, 0, byData.Length);
aFile.Close();
But this way the package remains open and i cant work with files it has used.
The save as will close the package properly, but its not accepting my file path.
Edit
I tried this:
using (FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xlsx", FileMode.Create))
{
byte[] byData = package.GetAsByteArray();
aFile.Seek(0, SeekOrigin.Begin);
package.SaveAs(aFile);
//aFile.Write(byData, 0, byData.Length);
aFile.Close();
}
But Get the following error?
Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package.
The package will be closed & disposed after you call any of functions GetAsByteArray, Save, SaveAs. That is the reason why you got message
Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package.
The solution is that after the saving you call Load function to continue processing on excel file. Or if you just want to get both ByteArray & FileOutput, I'm sure with you they both are same.
You can read data after have saved file to the disk:
string path = #"C:\test1.xlsx";
Stream stream = File.Create(path);
package.SaveAs(stream);
stream.Close();
byte[] data = File.ReadAllBytes(path);
Or you can save data to disk after get the ByteArray:
byte[] data = package.GetAsByteArray();
string path = #"C:\test1.xlsx";
File.WriteAllBytes(path, data);
I came looking for the answer to this but the existing answers were not clear to me.
Here is what I did using EPPlus and System.Windows.Forms:
ExcelPackage xlPackage = new ExcelPackage(xlsTmpFileName)
// Populate the Excel spreadsheet here.
SaveFileDialog sfd = new SaveFileDialog();
using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
{
xlPackage.SaveAs(fs);
}
I dont know from which version onwards but EPPlus's SaveAs method accepts a FileInfo. So you could do something like this:
using (var app = new ExcelPackage(new FileInfo(inputPath)))
{
//process
app.SaveAs(new FileInfo(outputPath));
}
Unlike the Save method SaveAs method overwrites file as well in case file name already exists.
SaveAs would be accepting your aFile Stream.
You can find out such things yourself by looking at the function signature: SaveAs(System.IO.Stream). It takes a Stream. Passing a string cannot possibly compile so you have to somehow make up a useful Stream (which you did).
Get rid of the surplus package.GetAsByteArray call and you should solve it.
I just ran:
using (FileStream aFile = new FileStream(#"C:\Temp\asdf.xlsx", FileMode.Create))
{
aFile.Seek(0, SeekOrigin.Begin);
package.SaveAs(aFile);
aFile.Close();
}
// See here - I can still work with the spread sheet.
var worksheet = package.Workbook.Worksheets.Single();
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
I am using following code to zip a file and it works fine but when I decompress with WinRar I get the original file name without the extension, any clue why if filename is myReport.xls when I decompress I get only myReport ?
using (var fs = new FileStream(fileName, FileMode.Open))
{
byte[] input = new byte[fs.Length];
fs.Read(input, 0, input.Length);
fs.Close();
using (var fsOutput = new FileStream(zipName, FileMode.Create, FileAccess.Write))
using(var zip = new GZipStream(fsOutput, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
zip.Close();
fsOutput.Close();
}
}
GZip compresses only one file - without knowing the name. Therefore if you compress the file myReport.xls you should name it myReport.xls.gz. On decompression the last file extension will be removed so you end up with the original filename.
That its the way how it is used in Unix/Linux for ages...
Very weird indeed. A brief search came up with the following:
http://dotnetzip.codeplex.com/discussions/268293
Which says that GZipStream has no way of knowing the name of the stream that is being written, and suggests you set the FileName property directly.
Hope that helps.