This is for a Windows Console App
I am saving an Excel file that I am using as a template for reports as a Base64 string. using the code below to encode the file as a base64 string. I then store it in an SQL Database as NVARCHAR(MAX)
Stream myStream = null;
string base64String;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
MemoryStream ms = new MemoryStream();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
using (myStream)
{
myStream.CopyTo(ms);
byte[] excelBytes = ms.ToArray();
base64String = Convert.ToBase64String(excelBytes, Base64FormattingOptions.None);
FileNameTxt.Text = openFileDialog1.FileName;
}
I then retrieve this file and decode the string and create a ClosedXML excel file.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
StoredFile = reader["StoredFile"].ToString();
}
reader.Close();
wb = workBook(StoredFile);
}
public static XLWorkbook workBook(string File)
{
byte[] data = System.Convert.FromBase64String(File);
MemoryStream ms = new MemoryStream(data);
XLWorkbook wb = new XLWorkbook(ms);
return wb;
}
The problem is that the end result is a workbook that has lost some of its formatting. mainly appears to have only affected border formatting.
I don't know if it is an issue with the encoding, decoding or generation of new file using ClosedXML that is causing the issue. Any direction or thoughts are greatly appreciated.
Related
I'm creating and downloading a .zip folder with images inside, but the images are damaged or corrupted and I don´t know how to fix it.
try{
byte[] retVal = null;
query = "Select query";
OrderList = BringDeliveryImageDirectories(query);
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var list in orderList)
{
ImageName = list.getImgFrontDni_tr().Split("/");
var file1 = archive.CreateEntry(imageName[5]);
using(BinaryWriter streamWriter = new BinaryWriter(file1.Open()))
{
streamWriter.Write(System.IO.File.ReadAllBytes("wwwroot" + list.getImgFrenteDni_tr()),0,("wwwroot" + list.getImgFrenteDni_tr()).Length);
streamWriter.Close();
}
ImageName = list.getImgDniDni_tr().Split("/");
var file2 = archive.CreateEntry(imageName[5]);
using(BinaryWriter streamWriter = new BinaryWriter(file2.Open()))
{
streamWriter.Write(System.IO.File.ReadAllBytes("wwwroot" + list.getImgDorsoDni_tr()),0, ("wwwroot" + list.getImgDorsoDni_tr()).Length);
streamWriter.Close();
}
}
memoryStream.Position = 0;
}
retVal = memoryStream.ToArray(); //
//return File(memoryStream, "application/zip", "Images.zip");
}
}
return File(retVal, MediaTypeNames.Application.Zip, "Images.zip");
}
I tried changing the BinaryWriter with StreamWriter, the Return File(), streamWriter.Write parameters, but nothing is fixing my problem, I searched here in Stack forum but didn't work for me.
The .zip folder is downloading and bringing all the images okey, but when I try to open an image, it says:
The image can´t open because format not compatible or damage
or also I have a popup again trying to open an image
Error to compress the folder. Windows cannot complete the extraction. Failed to create destiny file
my problem is that I can't figure out how to load a Canvas type object from an XML file. I hope you can help me.
This is what I was trying, I'll show you the code of how I'm doing the serialization too, just in case I did something wrong.
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "XML Files(*.xml) | *.xml | Text Files(*.txt) | *.txt | All Files(*.*) | *.* ";
sfd.ShowDialog();
MainWindow mainWindow = new MainWindow();
SerializeToXML(mainWindow, designSpace, 96, sfd.FileName);
mainWindow.Close();
}
public static void SerializeToXML(MainWindow window, Canvas canvas, int dpi, string filename)
{
string mystrXAML = XamlWriter.Save(canvas);
FileStream filestream = File.Create(filename);
StreamWriter streamwriter = new StreamWriter(filestream);
streamwriter.Write(mystrXAML);
streamwriter.Close();
filestream.Close();
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
var fileContent = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
ofd.FilterIndex = 2;
ofd.RestoreDirectory = true;
ofd.ShowDialog();
var fileStream = ofd.OpenFile();
string boi = ofd.FileName;
// Create an instance of the XmlSerializer specifying type.
XmlSerializer serializer =
new XmlSerializer(typeof(Canvas));
// Create a TextReader to read the file.
FileStream fs = new FileStream(boi, FileMode.Open);
TextReader reader = new StreamReader(fs);
// Use the Deserialize method to restore the object's state.
designSpace = (Canvas)serializer.Deserialize(reader);
}
The app works well until I try to load an XML file, that's when this exception pops out:
System.InvalidOperationException: 'Error to reflect type System.Windows.Controls.Canvas'.'
NotSupportedException: Can not serialize the member
System.Windows.Input.InputBinding.Command type
System.Windows.Input.ICommand because it's an interface.
I did
in Saving:
string xml = XamlWriter.Save(cssave);
using (StreamWriter fl = new StreamWriter(path, false))
{
fl.Write(xml);
}
In Loading:
string xml = File.ReadAllText(currpath);
//Convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
MemoryStream stream = new MemoryStream(byteArray);
Canvas cs = (Canvas)XamlReader.Load(stream);
csmain.Children.Add(cs);
How do I get C# to force bitmap images that are saved to be saved as 24-bit images as can be seen when you get the right-click properties of the image in Windows. All the images I save are set to 32-bit. I tried the below code with no luck. The source images are all 24-bit as well but are always saved as 32-bit image
public void Save(int index)
{
string savestrFilename;
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "image save...";
dialog.OverwritePrompt = true;
dialog.Filter = "JPEG File(*.jpg)|*.jpg|Bitmap File(*.bmp)|*.bmp";
if (dialog.ShowDialog() == DialogResult.OK)
{
savestrFilename = dialog.FileName;
System.IO.FileStream stream = new System.IO.FileStream(savestrFilename , System.IO.FileMode.Create);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 70;
encoder.Frames.Add(BitmapFrame.Create(_grabImageList[index].BitmapImage));
encoder.Save(stream);
stream.Close();
}
}
I got a strange error with this program, It download a photo from internet, then I convert it to .jpeg and then I delete the first photo (in .png).
But i got an error: File is being used by another process. Why is happening this? I didn't open the file, and nobody is using it.
string outFile;
outFile = Path.GetTempFileName();
try
{
webClient.DownloadFile(foto, outFile);
if (foto.Substring(foto.Length - 3) == "png")
{
System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile);
foto = foto.Remove(foto.Length - 3) + "jpg";
string outFile2 = Path.GetTempFileName();
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
System.IO.File.Delete(outFile);
outFile = outFile2;
}
}
FromFile is keeping the file open, you have to use something like this:
// Load image
FileStream filestream;
filestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);
currentImage = System.Drawing.Image.FromStream(filestream);
filestream.Close();
The system.Drawing.Image is holding on to the file, Just wrap the image1 in a using statement.
string foto = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons/64/Style-Config-icon.png";
string outFile = Path.GetTempFileName();
WebClient webClient = new WebClient();
try
{
webClient.DownloadFile(foto, outFile);
if (Path.GetExtension(foto).ToUpper() == ".PNG")
{
string outFile2 = Path.GetTempFileName();
using (System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile))
{
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
}
System.IO.File.Delete(outFile);
}
}
I'm trying to create an excel file and make that available as download. But i have some trouble with the download part.
I'm using EPPlus to create an xml file. I've got that working. But just local. I'm not sure how to force the download of the file.
This is my code:
public Stream GetXlsxDocument(IQueryable data)
{
const string sheetName = "Sheet1";
var localFile = new FileInfo(#"C:\test2.xlsx");
var file = new FileInfo("test2.xlsx");
// Used for local creation
//ExcelPackage p = new ExcelPackage();
MemoryStream stream = new MemoryStream();
using (ExcelPackage p = new ExcelPackage(stream))
{
p.Workbook.Worksheets.Add("Sheet1");
ExcelWorksheet ws = p.Workbook.Worksheets[1];
ws.Name = sheetName;
ws.Cells.Style.Font.Size = 11;
ws.Cells.Style.Font.Name = "Calibri";
ws.SetValue(1, 1, "aaa"); // Test data
// Used for local creation
//p.SaveAs(localFile);
p.SaveAs(stream);
}
return stream;
}
Like i said before. Creating the xlsx file locally on my C:\ disk works. But how can i force the download of the created xlsx file?
Right now its giving me an xlsx file of 0 bytes. I'd need to return a stream which isn't empty. Anyone any idea how i can do this..??
rewind it:
stream.Position = 0;
return stream;