I am trying to use SharpZip.unzipper for my windows phone 8.1. However it is not reading some of the code. Since i am fairly new to windows phone development please let me know the alternatives of following code for WP8.1
using System.Windows.Resources;
public Stream GetFileStream(string filename)
{
if (fileEntries == null)
fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like
long position = this.stream.Position;
this.stream.Seek(0, SeekOrigin.Begin);
Uri fileUri = new Uri(filename, UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(this.stream, null);
StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri);
this.stream.Position = position;
if (stream != null)
return stream.Stream;
return null;
}
Windows.Resources seems missing
I can't call StreamResourceInfo, System.Windows.Application
I have tried using App. but there is no function for GetResourceSteam
I am not sure what to do here
There are quite a few differences between WP8.1 runtime and WP8.1 Silverlight.
The code sample that you have will run on WP8.0 SL and WP8.1 SL.
It looks like you created a Windows Phone 8.1 runtime project. There is no System.Windows.Application.GetResourceStream()
Either convert it to a compatible 8.1 runtime stream or recreate your project to target Silverlight instead.
// sample
private async void ZipLibraryTest()
{
// create the full path
string zip = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "filename.zip");
// create the storage file with the file name
StorageFile sf = await StorageFile.GetFileFromPathAsync(zip);
// create the IO Stream
using (System.IO.Stream output = await sf.OpenStreamForWriteAsync())
{
// open the zip file for writing, use the stream from the file
ZipFile zf = ZipFile.Create(output);
// rest of your code
// ...
// ...
// close the zip file
zf.Close();
}
}
Related
I need Xamarin to call a GET API that downloads a photo from a url and save it in the phone.
When xamarin calls the API, it will download a image from a url and then return it as response to xamarin, after this I will save the photo in the phone.
The API is a C# 4.0 MVC. I created a Get API that downloads the image successfully and returns it as FileStreamResult.
The API downloads the image from a url and return it
public FileStreamResult DownloadFoto()
{
Stream rtn = null;
string aURL = "https://image.shutterstock.com/image-vector/sample-stamp-grunge-texture-vector-260nw-1389188336.jpg";
HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(aURL);
HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
rtn = aResponse.GetResponseStream();
return File(rtn, "image/jpeg", foto);
}
Xamarin Forms
HttpConnectionis an instance of HttpClient.
var Response = await Application.HttpConnection.GetAsync("DownloadFoto");
DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", Response.Content.ReadAsStreamAsync().Result, "imagesFolder");
Xamarin Android
[assembly: Dependency(typeof(FileService))]
namespace Diario.Droid
{
public class FileService : IFileService
{
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
}
}
I don't get any error, it looks to be saving the image, but when I look for it in File Management I don't find the image there.
Yeah the directory path your are getting with:
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
It is pointing at somewhere in /data/user/ which will be private to the App. If you want to make it browse-able using a File Explorer App, you will probably need to save it somewhere in External Storage (public storage).
You can get a path for that with:
var externalDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);
If you are targeting Android API 18 and lower, remember to add permissions for that in your AndroidManifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
Since some devices on Android can have their External Storage on microSD cards, you will need to check whether you can write to it first:
var stateOk = Android.OS.Environment.ExternalStorageState == Android.OS.Environment.MediaMounted;
if (stateOk)
{
// I can write!
}
From Android API 23 and up, you will need to request permission before being able to read and write to external storage. You could use this plugin to easily ask for permissions: https://github.com/jamesmontemagno/PermissionsPlugin
Another couple of things to notice. You are using .Result on your ReadAsStreamAsync() call. Just keep in mind that you will be blocking the thread you are on. I highly suggest you design your methods to be async all the way.
I have a Universal Windows application that hosts a main menu. I want a plugin architecture, where the menu items are added from class libraries.
But I can't seem to load images correctly. I can't get the ms-appx:/// working, and when I try to add the images as an embedded resource, it hangs:
var assembly = typeof(CookModule).GetTypeInfo().Assembly;
using (var imageStream = assembly.GetManifestResourceStream("My.Namespace.Folder.ImageName-100.png"))
using (var raStream = imageStream.AsRandomAccessStream())
{
var bitmap = new BitmapImage();
bitmap.SetSource(raStream); //<- Hangs here
I get no exceptions, errors in the output or anything. It just hangs there, and the app simply doesn't load the page.
I have also tried:
var bitmap = new BitmapImage(new Uri("/Folder/ImageName-100.png"));
I'm missing something similar to the WPF pack uri's where I can state which assembly to load the image from.
What is the correct (and working) way of adding a image resource to a Page from a class libary? (Or does anyone have a working example of ms-appx where the image is in a class library)
I can reproduce this issue. Current workaround I used is copying the resource stream to .NET memory stream.
var assembly = typeof(CookModule).GetTypeInfo().Assembly;
using (var imageStream = assembly.GetManifestResourceStream("UWP.ClassLibrary.210644575939381015.jpg"))
using (var memStream = new MemoryStream())
{
await imageStream.CopyToAsync(memStream);
memStream.Position = 0;
using (var raStream = memStream.AsRandomAccessStream())
{
var bitmap = new BitmapImage();
bitmap.SetSource(raStream);
display.Source = bitmap;
}
}
I am converting an app from WP7 to WP8.1 The codes for WP7 no longer works for WP8.1
sfxLeft = new MediaElement();
sfxRight = new MediaElement();
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri(wav, UriKind.Relative));
var sfx = SoundEffect.FromStream(streamInfo.Stream);
sfxLeft = sfx.CreateInstance();
sfxRight = sfx.CreateInstance();
StreamResourceInfo does not exists for WP8.1 anymore. Anyone know how I can re-write this line to make it work for WP8.1?
Updated Code.
Here's the new code below, but now it seems the sfxLeft and sfxRight are always NULL. I thought the below code would set sfxLeft and sfxRight, but it's still NULL.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
test();
}
async private Task test()
{
Uri wav = new Uri("ms-appx:///Assets/eye_poke.wav", UriKind.RelativeOrAbsolute);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(wav);
stream = await file.OpenStreamForReadAsync();
sfxLeft = SoundEffect.FromStream(stream).CreateInstance();
sfxRight = SoundEffect.FromStream(stream).CreateInstance();
}
To play sound using XNA Framework in Windows Phone 8.1 Silverlight App
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(wav);
Stream stream = await file.OpenStreamForReadAsync();
SoundEffect Sound1 = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
Sound1.Play();
Or you can use MediaElement for both RT and Silverlight but they are in different namespace,
MediaElement mediaElement1 = new MediaElement();
mediaElement1.Source = wav
mediaElement1.AutoPlay = false;
rootGrid.Children.Add(mediaElement1)
Thanks. I figured it out by using the media element in XAML and then add codes in c# to play it.
I am trying to develop a simple Windows 8 Metro app which simply downloads an image file from a given URL (say http://sample.com/foo.jpg) and then save it to Pictures Library.
I have an image control in the UI to display the downloaded image.
I'm also facing difficulty in setting the image source for the image control to the newly downloaded image (actually I'm not even able to download it).
Also, is it possible to store the image file in a particular folder in the Pictures library (if it doesn't exist, then the app should create it)?
I'm really stuck here.
Please help me.
Here's some rough code that I believe accomplishes what you want. It assumes you have two image controls (Image1 and Image2) and that you have the Pictures Library capability checked in the manifest. Take a look at the XAML images sample as well
Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg");
var fileName = Guid.NewGuid().ToString() + ".jpg";
// download pic
var bitmapImage = new BitmapImage();
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(uri);
byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
// create a new in memory stream and datawriter
using (var stream = new InMemoryRandomAccessStream())
{
using (DataWriter dw = new DataWriter(stream))
{
// write the raw bytes and store
dw.WriteBytes(b);
await dw.StoreAsync();
// set the image source
stream.Seek(0);
bitmapImage.SetSource(stream);
// set image in first control
Image1.Source = bitmapImage;
// write to pictures library
var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName,
CreationCollisionOption.ReplaceExisting);
using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
}
}
}
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using ( var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read) )
{
bitmapImage.SetSource(pictureStream);
}
Image2.Source = bitmapImage;
}
I have a zip password file and know this password.
I need open this zip file in Windows 8 metro app program code.
But 'System.IO.Compression.ZipArchive' is not supported decompress zip with password in Windows 8 metro app program code.
I'm try SharpZipLib and DotNetZip. BUT they are not support net 4.5. So i doesn't use them in my metro program code.
I'm try Ionic.Zip. It's ok in program code. I want to build packages to upload to the windows store. But not pass in microsoft code review.
Is there another way?
thanks a lot
The System.IO.Compression.FileSystem assembly is not available for Windows Store apps, so you cannot use the ExtractToDirectory extension method of the ZipFileExtensions class.
Instead of DirectoryInfo, FileInfo, etc. use StorageFile. See Accessing data and files and the File access sample for more information on how to read and write files in Metro style apps. Then you'll need to read the data from the file into a stream and then pass that to methods of one of the following class (your choice):
DeflateStream (which internally uses zlib as of .NET 4.5)
ZipArchive or GZipStream classes. Those are available to Metro style apps, even if the file specific extension methods are not.
Windows Runtime type Decompressor to decompress files.
you can using https://sharpcompress.codeplex.com/.
it support open file zip have password
code bellow
//if file zip have a file pdf , a file xml
async void Read(StorageFile file)
{
MemoryStream memoryFilePDf = new MemoryStream();
MemoryStream memoryFileXml = new MemoryStream();
FilePdf = null;
FileXml = null;
using (var zipStream = await file.OpenStreamForReadAsync())
{
using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
{
await zipStream.CopyToAsync(zipMemoryStream);
try
{
using (var archive = ZipArchive.Open(zipMemoryStream, PassWord))
{
bool isFilePdf = false;
foreach (var entry in archive.Entries)
{
if (!entry.Key.ToLower().EndsWith(".pdf") && !entry.Key.ToLower().EndsWith(".xml"))
{
continue;
}
if (entry.Key.ToLower().EndsWith(".pdf"))
{
isFilePdf = true;
entry.WriteTo(memoryFilePDf);
}
else
{
isFilePdf = false;
entry.WriteTo(memoryFileXml);
}
var fileName = entry.Key.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
var createFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream stream = await createFile.OpenAsync(FileAccessMode.ReadWrite))
{
// Write compressed data from memory to file
using (Stream outstream = stream.AsStreamForWrite())
{
byte[] buffer = isFilePdf ? memoryFilePDf.ToArray() : memoryFileXml.ToArray();
outstream.Write(buffer, 0, buffer.Length);
outstream.Flush();
}
}
if (isFilePdf)
{
FilePdf = createFile;
}
else
{
FileXml = createFile;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}