Store Image in DataTable - wpf

I want to store image into my datatable and while adding colum I want to set its default value, sending you code doing with checkboxes..
public void addCheckBoxesRuntime(){
for (int i = 0; i < InformationOne.Length; i++)
{
dt = new DataColumn(InformationOne[i][1] + " (" + InformationOne[i][0] + " )");
dt.DataType = typeof(Boolean);
viewDataTable.Columns.Add(dt);
dt.DefaultValue = false;
}
}

Make a DataColumn with type string and then store the string binary of the image into the field. Alternatively, use the binary itself with a byte[].
Should work 100%.
Something along the lines of this:
public string ImageConversion(System.Drawing.Image image)
{
if (image == null)
return string.Empty;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);
string value = string.Empty;
for (int intCnt = 0; intCnt <= memoryStream.ToArray.Length - 1; intCnt++)
{
value = value + memoryStream.ToArray(intCnt) + ",";
}
return value;
}
}

Related

How to get all PDF files Uri with FileName from external storage in Android 10 using java

I am trying to list all the PDF files from the external storage created by the app. How to list pdf files in the App after iterating through cursor?
private void getExternalPDFFiles() {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
// every column, although that is huge waste, you probably need
// BaseColumns.DATA (the path) only.
String[] projection = null;
// exclude media files, they would be here also.
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE;
String[] selectionArgs = null; // there is no ? in selection so null here
String sortOrder = null; // unordered
// Cursor allNonMediaFiles = cr.query(uri, projection, selection, selectionArgs, sortOrder);
// only pdf
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String[] selectionArgsPdf = new String[]{mimeType};
Cursor cursor = cr.query(uri, projection, selectionMimeType, selectionArgsPdf, sortOrder);
assert cursor != null;
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//your code to implement
Log.d("TAG", cursor.getColumnNames().toString());
cursor.moveToNext();
}
}
Log.d("TAG", cursor.getCount() + "");
Log.d("TAG", cursor.getColumnCount() + "");
cursor.close();
}
Get all file list with Uri and FileName in Android-10 and above:
class FileModel {
String displayName;
Uri fileUri;
FileModel(String displayName, Uri fileUri) {
this.displayName = displayName;
this.fileUri = fileUri;
}
}
...
private ArrayList<FileModel> getExternalPDFFileList() {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE;
String[] selectionArgs = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String[] selectionArgsPdf = new String[]{mimeType};
Cursor cursor = cr.query(uri, projection, selectionMimeType, selectionArgsPdf, null);
assert cursor != null;
ArrayList<FileModel> uriList = new ArrayList<>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
long fileId = cursor.getLong(columnIndex);
Uri fileUri = Uri.parse(uri.toString() + "/" + fileId);
String displayName = cursor.getString(cursor.getColumnIndex(projection[1]));
uriList.add(new FileModel(displayName, fileUri));
}
cursor.close();
return uriList;
}

How to stop other conditional formatting from disappearing when hackmodding databars into solid fills?

EPPlus has no support for extLst thing which is needed to make databars conditional formatting with solid fill. They are gradient by themselves without modifications.
I coded this to modify worksheet's xml directly (this gets databars from worksheet XML and then adds required extLst nodes):
public static Random Rnd = new Random();
public static string GenerateXlsId()
{
//{29BD882A-B741-482B-9067-72CC5D939236}
string id = string.Empty;
for (int i = 0; i < 32; i++)
if (Rnd.NextDouble() < 0.5)
id += Rnd.Next(0, 10);
else
id += (char)Rnd.Next(65, 91);
id = id.Insert(8, "-");
id = id.Insert(13, "-");
id = id.Insert(18, "-");
id = id.Insert(23, "-");
return id;
}
public static void FixDatabarsAtWorksheet(OfficeOpenXml.ExcelWorksheet eworksheet)
{
System.Xml.XmlNodeList databars = eworksheet.WorksheetXml.GetElementsByTagName("dataBar");
if (databars.Count > 0)
{
string conditional_formattings_str = string.Empty;
for (int i = 0; i < databars.Count; i++)
{
string temp_databar_id = GenerateXlsId();
databars[i].ParentNode.InnerXml += #"<extLst>
<ext uri=""{B025F937-C7B1-47D3-B67F-A62EFF666E3E}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:id>{" + temp_databar_id + #"}</x14:id>
</ext>
</extLst>";
//--
string temp_sqref = databars[i].ParentNode.ParentNode.Attributes["sqref"].Value;
string left_type = string.Empty;
string left_val = string.Empty;
string right_type = string.Empty;
string right_val = string.Empty;
string color = string.Empty;
Color databar_fill_color = Color.Empty;
Color databar_border_color = Color.Empty;
for (int j = 0; j < databars[i].ChildNodes.Count; j++)
if (databars[i].ChildNodes[j].LocalName == "cfvo" && databars[i].ChildNodes[j].Attributes["type"] != null)
{
if (string.IsNullOrEmpty(left_type))
left_type = databars[i].ChildNodes[j].Attributes["type"].Value;
else if (string.IsNullOrEmpty(right_type))
right_type = databars[i].ChildNodes[j].Attributes["type"].Value;
if (databars[i].ChildNodes[j].Attributes["val"] != null)
if (string.IsNullOrEmpty(left_val))
left_val = databars[i].ChildNodes[j].Attributes["val"].Value;
else if (string.IsNullOrEmpty(right_val))
right_val = databars[i].ChildNodes[j].Attributes["val"].Value;
}
else if (databars[i].ChildNodes[j].LocalName == "color")
{
color = databars[i].ChildNodes[j].Attributes["rgb"].Value;
int argb = Int32.Parse(color, System.Globalization.NumberStyles.HexNumber);
databar_fill_color = Color.FromArgb(argb);
databar_border_color = Color.FromArgb(255,
databar_fill_color.R - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.R - 50,
databar_fill_color.G - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.G - 50,
databar_fill_color.B - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.B - 50);
}
string temp_conditional_formatting_template = #"<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{" + temp_databar_id + #"}"">
<x14:dataBar minLength=""" + (string.IsNullOrEmpty(left_val) ? "0" : left_val) + "\" maxLength=\"" + (string.IsNullOrEmpty(right_val) ? "100" : right_val) + "\" gradient=\"0\" " + (databar_border_color.IsEmpty ? string.Empty : "border = \"1\"") + ">";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (left_type.ToLower() == "min" ? "autoMin" : left_type) + "\" />";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (right_type.ToLower() == "max" ? "autoMax" : right_type) + "\" />";
if (!databar_border_color.IsEmpty)
temp_conditional_formatting_template += Environment.NewLine + "<x14:borderColor rgb=\"" + BitConverter.ToString(new byte[] { databar_border_color.A, databar_border_color.R, databar_border_color.G, databar_border_color.B }).Replace("-", "") + "\" />";
temp_conditional_formatting_template += Environment.NewLine + #"</x14:dataBar>
</x14:cfRule>
<xm:sqref>" + temp_sqref + #"</xm:sqref>
</x14:conditionalFormatting>";
conditional_formattings_str += temp_conditional_formatting_template;
}
databars[0].ParentNode.ParentNode.ParentNode.InnerXml += #"<extLst>
<ext uri=""{78C0D931-6437-407d-A8EE-F0AAD7539E65}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:conditionalFormattings>" + conditional_formattings_str + #"
</x14:conditionalFormattings>
</ext>
</extLst>";
}
}
And this really makes databars solid fill, the problem is any other conditional formatting like GreaterThan loses it's style when true.
For example I add databar and GreaterThan 123 (green) conditional formattings.
Excel still see coditional formatting rule GreaterThan 123, but the style is not set when it's true (green is not set). While databars is displayed correctly at same time.
I don't know where to look... Someone help!
Thats the problem with hacks - they are so fragile! :)
I was able to get it work with another hack - setting the style differential formatting (dxf) reference which seems to be dropped when epplus saves. What might be happening is epplus only thinks there is one dxf on save so it doesnt set the value since excel will assume it is the first dxf style (index 0) but that is a bit of a guess.
Anyway, if you set the dxfid via XML manually it will find it. But order counts here, you have to apply the databar hack last otherwise it will hit the wrong reference:
[TestMethod]
public void FixDatabarsAtWorksheetTest()
{
//https://stackoverflow.com/questions/58417819/how-to-stop-other-conditional-formatting-from-disappearing-when-hackmodding-data
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]
{
new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = i;
row[1] = i * 10;
row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(#"c:\temp\FixDatabarsAtWorksheetTest.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var doc = workbook.Worksheets.Add("Sheet1");
doc.Cells.LoadFromDataTable(datatable, true);
//Set the greater than
var gtConditional = doc
.ConditionalFormatting
.AddGreaterThan(doc.Cells["A2:A11"]);
gtConditional.Formula = "2";
gtConditional.Style.Fill.BackgroundColor.Color = Color.GreenYellow;
//Fix the gt
var xdoc = doc.WorksheetXml;
var nsm = new XmlNamespaceManager(xdoc.NameTable);
nsm.AddNamespace("default", xdoc.DocumentElement.NamespaceURI);
var gtNode = xdoc.SelectSingleNode("/default:worksheet/default:conditionalFormatting[#sqref=\"A2:A11\"]", nsm);
//Create the new attribute for table
var att = xdoc.CreateAttribute("dxfId");
att.Value = "0";
gtNode
.FirstChild
.Attributes.Append(att);
//Set the bar condition LAST
var barConditional = doc
.ConditionalFormatting
.AddDatabar(doc.Cells["B2:B11"], Color.FromArgb(99, 195, 132));
barConditional.HighValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.LowValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.HighValue.Value = 82;
barConditional.LowValue.Value = 0;
FixDatabarsAtWorksheet(doc);
pck.Save();
}
}
I get this:
Not sure how feasible this is for you depending on how many conditional formats you have but its worth a shot.

Comma separated string split by length but keeping the comma separation?

I have a string like this "105321,102305,321506,0321561,3215658" and i need to split this string by the comma (,) and with a specific length, so if the length of each string part is 15, the splited array must be like:
105321,102305
321506,0321561
3215658
I try several ways but i can't find the right approach to do this
The code that i have gives me an error of index out of range:
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
for(int i = 0; i < firstSplit.Length; i++)
{
string part = firstSplit[i];
if(output.Any() && output[i].Length + part.Length >= maxSplit)
{
output.Add(part);
}
else
{
if(!output.Any())
output.Add(part);
else
output[i] += "," + part;
}
}
return output;
}
Edit: i must say that the comma , must be a part of the amount of the maxSplit variable.
This one would be concise, yet not really performant
private static Pattern P = Pattern.compile("(.{1,15})(,|$)");
private static String[] split(String string) {
Matcher m = P.matcher(string);
List<String> splits = new ArrayList<String>();
while (m.find()) {
splits.add(m.group(1));
}
return splits.toArray(new String[0]);
}
The regular expression in P matches (.{1,15})(,|$):
a sequence of 1 to 15 characters = .{1,15}
followed by , or line ending
the parentheses allow grouping, the content of the first group is what you are interested in
static void Main(string[] args)
{
string originalString = "105321,102305,321506,0321561,3215658";
string[] commaSplit = originalString.Split(',');
string tempString = string.Empty;
List<string> result = new List<string>();
for (int i = 0; i < commaSplit.Length; i++ )
{
if ((tempString.Length + commaSplit[i].Length) > 15)
{
result.Add(tempString);
tempString = string.Empty;
}
if (tempString.Length > 0)
{
tempString += ',' + commaSplit[i];
}
else
{
tempString += commaSplit[i];
}
if (i == commaSplit.Length - 1 && tempString != string.Empty)
{
result.Add(tempString);
}
}
foreach (var s in result)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
This may not be the best solution but it works ;)
what about this?
private static List<string> SplitThis(char charToSplit, string text, int maxSplit)
{
List<string> output = new List<string>();
string[] firstSplit = text.Split(charToSplit);
int i = 0;
while (i < firstSplit.Length)
{
string part = firstSplit[i];
while (part.Length < maxSplit)
{
if (part.Length < maxSplit && i + 1 < firstSplit.Length)
{
if ((part + "," + firstSplit[i + 1]).Length < maxSplit)
{
part += "," + firstSplit[i + 1];
i++;
}
else
{
output.Add(part);
i++;
break;
}
}
else
{
output.Add(part);
i++;
break;
}
}
}
return output;
}

C# Windows Application Image Resizing Before Saving

I have this Code to Save a Pic to my Solution Explorer Images Folder.
private void btnUploadImage_Click(object sender, EventArgs e)
{
//The String used to store the location of the file that is currently loaded in the picture box picFile
String location;
//The String used to store the name of the file that is currently loaded in the picture box picFile
String fileName;
ofdImageUpload.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
//Showing the fileopen dialog box
ofdImageUpload.ShowDialog();
//showing the image opened in the picturebox
imgCapture.Image = new Bitmap(ofdImageUpload.FileName);
//storing the location of the pic in variable
location = ofdImageUpload.FileName;
txtImgLocation.Text = location;
//storing the filename of the pic in variable
fileName = ofdImageUpload.SafeFileName;
//pictureboxImage.Image.Save();
imgCapture.SizeMode = PictureBoxSizeMode.StretchImage;
if (imgCapture.Image != null)
{
lblHiddenMsg.Text = "";
}
}
private void InsertGatepassEntry(int RowId)
{
string ContName = txtContName.Text.Trim();
string ContAdd = richtxtContAddress.Text.Trim();
string VisitorName = txtEmpName.Text.Trim();
string VisitorAdd = txtEmpAddress.Text.Trim();
string VisitorFathersName = txtEmpFatherName.Text.Trim();
string VisitorAge = txtEmpAge.Text.Trim();
string VisitorEsi = txtEsi.Text.Trim();
string VisitorContact = txtEmpContactNo.Text.Trim();
string VisitorBloodGrp = comboxBloodGroup.SelectedText.Trim();
string VisitorIssueDate = dtpEmpDateOfIssue.Text.Trim();
string imagename = ofdImageUpload.SafeFileName;
if (imagename != null || imagename != "") //Check If image is Selected from Computer's Hard Drive
{
if (imgCapture.Image != null)
{
//string imagepath = ofdImageUpload.FileName;
//string picname = imagepath.Substring(imagepath.LastIndexOf('\\'));
string picname = imagename;
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
Bitmap imgImage = new Bitmap(imgCapture.Image); //Create an object of Bitmap class/
//string fullPathName = path + "Images" + picname;
imgImage.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
string Image = "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
else
{
lblHiddenMsg.Visible = true;
lblHiddenMsg.Text = "Please capture or browse an image First";
}
}
else //image is directly uploding from Webcam Capture
{
string Image = lblHiddenMsg.Text;
string GatepassNo = LoadLastGatepassNo();
switch (Contractor.InsertGatepassEntry(RowId, ContName, ContAdd, VisitorName, VisitorAdd, VisitorFathersName, VisitorAge, VisitorEsi, VisitorContact, VisitorBloodGrp, VisitorIssueDate, Image, GatepassNo))
{
case ProjectCreateStatus.Insertrow:
lblMessage.Text = "Information inserted successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
lblGatepassNo.Text = GatepassNo;
break;
}
}
}
private void bntCapture_Click(object sender, EventArgs e)
{
imgCapture.Image = imgVideo.Image;
Bitmap b = new Bitmap(imgCapture.Image);
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
b.Save(path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg");
lblHiddenMsg.Text = path + "Images\\" + txtEmpName.Text + txtEsi.Text + ".jpg";
}
Now I want to Save those uploaded Pic to my Images Folder to a particular Size like 250x250. can Anyone Help ? m new in Windows Application C#.
To resize your image use:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));
hi you can add the "Size" class as a parameter of your Bitmap constructor to resize the image
i did for you this function to make it easy hope that will help you
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
yourImage = resizeImage(yourImage, new Size(250,250));

How to save bitmapimage in Isolated storage?

I am developing silverlight web part by using the client object model. I am getting the bitmap image from sharepoint server. Now I want to save this bitmap image in isolated storage. So I am using following code
WriteableBitmap wb = new WriteableBitmap(attachments);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("abcd1.jpg", FileMode.Create, isoFile))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(wb.ToByteArray());
}
}
}
Now I am seeing the saved image at location C:\Users\Rent2\AppData\LocalLow\Microsoft\Silverlight\is\vzvpufsm.s4i\m0laonzr.til\1\s\nkhajster01es5wdoyfxd0n5rd2dls3ovyu4wcdig04zjx44hyaaafea\f
When I click on it, it gives me message as "Invalid Image". Can you please tell me how should i write code so that I can see the actual image after saving it in isolated storage ?
private void zipFile()
{
context = Microsoft.SharePoint.Client.ClientContext.Current;
Microsoft.SharePoint.Client.File.OpenBinaryDirect(
context,
#"/TemplateInvoice/" + App.templateFileName + ".xlsx", successFile, FailFile);
}
private void successFile(object sender, OpenBinarySucceededEventArgs args)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Obtain the isolated storage for an application.
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
Stream strm = args.Stream;
using (var isoStream = store.OpenFile(App.templateFileName + ".zip", FileMode.OpenOrCreate))
{
// Read the resource file into a byte array.
bytes = new byte[strm.Length];
int numBytesToRead = (int)strm.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = strm.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
// Write the byte array to the IsolatedStorageFileStream.
isoStream.Write(bytes, 0, numBytesToRead);
//isoStream.Dispose();
}
strm.Close();
string path = App.templateFileName + ".zip";
ZipHelp.UnZip(path, System.IO.Path.GetDirectoryName(path), 4096);
replaceFileContent();
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(path);
string fileName = ZipHelp.Zip(rootDirectory.Replace(".zip", ""), invoice);
//string filename = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "Invoice1.xlsx";
// Read the resource file into a byte array.
using (var stream = store.OpenFile(fileName, FileMode.Open))
{
bytes = new byte[stream.Length];
int numBytesToRead = (int)stream.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = stream.Read(bytes, numBytesRead, numBytesToRead);
// The end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
InvoiceTemplete invoiceTemplate = new InvoiceTemplete(fileName, bytes, SetMessage);
invoiceTemplate.AddDocument(invoiceTemplate);
}
}
//mark rows as billed
foreach (var item in PrivatePayList)
{
MedwaiverViewModel MedwaiverViewModelObj = new MedwaiverViewModel();
MedwaiverViewModelObj.ChangeBillingStatus(item.ListItemId, "Billed");
if (MedwaiverTimeLogList != null)
{
MedwaiverTimeLogList.Remove(item);
}
if (ClientSpecificTimeLogList != null)
{
ClientSpecificTimeLogList.Remove(item);
}
if (rangeBoundTimeLogListForDate != null)
{
rangeBoundTimeLogListForDate.Remove(item);
}
if (vRangeBoundTimeLogListForDateAndClient != null)
{
vRangeBoundTimeLogListForDateAndClient.Remove(item);
}
}
}
catch (IsolatedStorageException isx)
{
MessageBox.Show(isx.Message);
}
});
}
private void FailFile(object sender, OpenBinaryFailedEventArgs e)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Fail");
});
}
//The following class zip and unzip the file
class ZipHelp
{
static List<string> folderPathList = new List<string>();
public static string Zip(string rootDirectory, string fileName)
{
byte[] buffer;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream zipFileStream = store.CreateFile(fileName + ".xlsx");
ZipOutputStream zipOutStream = new ZipOutputStream(zipFileStream);
zipOutStream.UseZip64 = UseZip64.Off;
//zipOutStream.CanPatchEntries
foreach (var item in folderPathList)
{
string entryName = "";
buffer = new byte[4096];
if (item.Substring(0,1) == #"/")
{
//removes leading /
entryName = item.Substring(1);
}
else
{
entryName = item;
}
ZipEntry entry = new ZipEntry(entryName);
//entry.CompressionMethod = CompressionMethod.Deflated;
//entry.
entry.IsZip64Forced();
//entry.IsDirectory
zipOutStream.PutNextEntry(entry);
using (IsolatedStorageFileStream stream = store.OpenFile(rootDirectory + #"\" + item, FileMode.Open))
{
int size;
do
{
size = stream.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
stream.Close();
}
}
zipOutStream.Close();
zipFileStream.Close();
}
return fileName + ".xlsx";
//string[] directories = GetLocationTypes();
//zip();
//string[] filenames = Directory.GetFiles(directories);
//using (var store = IsolatedStorageFile.GetUserStoreForApplication())
//{
// using (var isoStream = store.OpenFile("#" + rootDirectory, FileMode.OpenOrCreate))
// {
// //foreach(string dir in
// }
//}
}
private static string[] GetLocationTypes()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
return store.GetDirectoryNames();
}
}
/// <summary>
/// UnZip a file
/// </summary>
/// <param name="SrcFile">source file path</param>
/// <param name="DstFile">unzipped file path</param>
/// <param name="BufferSize">buffer to use</param>
public static void UnZip(string SrcFile, string DstFile, int BufferSize)
{
folderPathList.Clear();
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamIn = store.OpenFile(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(SrcFile);
rootDirectory = rootDirectory.Replace(".zip", "");
store.CreateDirectory(rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!store.DirectoryExists(rootDirectory + "/" + folderPath))
{
store.CreateDirectory(rootDirectory + "/" + folderPath);
}
}
folderPath = folderPath + "/" + lastElement;
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, folderPath);
}
else
{
writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, entry.Name);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void writeToFile(int BufferSize, FileStream fileStreamIn, ZipInputStream zipInStream, string rootDirectory, string folderPath)
{
IsolatedStorageFile store1 = IsolatedStorageFile.GetUserStoreForApplication();
FileStream fileStreamOut = store1.OpenFile(rootDirectory + "/" + folderPath, FileMode.Create, FileAccess.Write);
folderPathList.Add(folderPath);
int size;
byte[] buffer = new byte[BufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
}
I can think of two viable options here.
In your code above, save off the Pixels array of the WriteableBitmap. Then to restore it, you would create a WriteableBitmap of the appropriate size and the set the Pixels array to the stored data.
-or-
Use a HttpWebRequest or WebClient request to get the raw image stream and save that to IsolatedStorage.
There are pros and cons to each of these, in the first case the data is uncompressed and will take up more space in isolated storage and you would not be able to open the image from disk outside of Silverlight, similar to the issue you had above. For the second option you can run into cross domain issues if the images are on a different server than your Silverlight XAP file and it's also a bit more complex to implement.
The basic problem is that you're storing the decoded RGBA pixels array as a JPEG file - but they're not the same. Your code is basically correct: you just can't use this method to store it as a JPEG file. But if you happen to know that the image is, say, 800x600, you could create an 800x600 WriteableBitmap, and then set the Pixels property to the retrieved stream's byte array. Or if you don't know the dimensions when you're retrieving it, you could store the dimensions as the first two integers in the stream (before you write the pixels to the stream), and read out the dimensions when you're reading the file. You'd effectively be creating your own very simplistic .bmp format.

Resources