Windows phone 8 download then unzip to isolated storage - windows-phone-8

I'm writing a windows phone 8 application that have following functions
Download a zip file from the internet
Extract it to the isolated storage
I'm looking for a solution to deal with it but haven't found once. If you have any suggestion please help.
Thanks in advance!
EDIT:
I break it down into several steps:
Check if storage is available - DONE
Check if file is compressed - DONE
Use Background Transfer (or another method) to download to local folder and display information to user (percentage, ect.) - NOT YET
Unzip file to desired location in isolated storage - NOT YET
Do stuffs after that... - DONE
For step 4, I found and modified some script to extract file to isolated storage (using SharpGIS.UnZipper lib):
public async void UnzipAndSaveFiles(Stream stream, string name)
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var zipStream = new UnZipper(stream))
{
foreach (string file in zipStream.FileNamesInZip)
{
string fileName = Path.GetFileName(file);
if (!string.IsNullOrEmpty(fileName))
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
folder = await folder.CreateFolderAsync("html", CreationCollisionOption.OpenIfExists);
StorageFile file1 = await folder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
//save file entry to storage
using (var writer = new StreamWriter(await file1.OpenStreamForWriteAsync()))
{
writer.Write(file);
}
}
}
}
}
}
This code is untested (since I haven't downloaded any file).
Can anyone point out any thing that should be corrected (enhanced)?
Can anyone help me to modify it to extract password-protected file (Obviously I have the key)?

Related

How to open local file from browser?

I'm using the following when trying to open a local file:
some document
When I click the above in a browser, it opens Finder to the folder. But does not open the file. Should I be doing something else to have the file open in Numbers?
You cannot open local files on the client. This would be a huge security risk.
You can link to files on your server (like you did) or you can ask the client for a file using <input type="file">
You can only open some types of files in browsers, like html css js and mp4, otherwise the browser will want to download it. Also remember that browsers replace spaces with %20. I recommend right clicking the file and opening it with chrome then copy that link and using it.
You can open files that are local as long as it is a file that is on the file that is trying to open another file is local.
Your issue is likely the space in the document name. Try this instead:
some document
The %20 will be read by your browser as a space.
Update
The other answer points out something I missed. The .numbers extension will not be able to be opened directly by your browser. Additionally the other answer describes the security risk this could create.
The File API in HTML 5 now allows you to work with local files directly from JS (after basic user interaction in selecting the file(s), for security).
From the Mozilla File API docs:
"The File interface provides information about files and allows JavaScript in a web page to access their content.
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement."
For more info and code examples, see the sample demo linked from the same article.
This might not be what you're trying to do, but someone out there may find it helpful:
If you want to share a link (by email for example) to a network file you can do so like this:
file:///Volumes/SomeNetworkFolder/Path/To/file.html
This however also requires that the recipient connects to the network folder in finder --- in menu bar,
Go > Connect to Server
enter server address (e.g. file.yourdomain.com - "SomeNetworkFolder" will be inside this directory) and click Connect. Now the link above should work.
Here is the alternative way to download local file by client side and server side effort:
<a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>
js:
function fileClick(a) {
var linkTag = a.href;
var substring = "file:///";
if (linkTag.includes(substring)) {
var url = '/v/downloadLocalfile?path=' +
encodeURIComponent(linkTag);
fileOpen(url);
}
else {
window.open(linkTag, '_blank');
}
}
function fileOpen(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log("Complete: [ " + txt_status + " ] " + jqxhr);
if (txt_status == 'success') {
window.open(url, '_self');
}
else {
alert("File not found[404]!");
}
// }
}
});
}
Server side[java]:
#GetMapping("/v/downloadLocalfile")
public void downloadLocalfile(#RequestParam String path, HttpServletResponse
response) throws IOException, JRException {
try {
String nPath = path.replace("file:///", "").trim();
File file = new File(nPath);
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;filename=" +
fileName);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
response.setStatus(200);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
// out.flush();
in.close();
out.close();
}
else {
response.setStatus(404);
}
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
}
return;
}
You can expose your entire file system in your browser by using an http server.
caddy2 server
caddy file-server --listen :2022 --browse --root /
serves the root file system at http://localhost:2022/
python3 built-in server
python3 -m http.server
serves current dir on http://localhost:8000/
python2 built-in server
python3 -m SimpleHTTPServer
serves current dir on http://localhost:8000/
This s

Windows Phone 8 choose text file C#

i have a question. If there is a possibility at windows phone 8 at visual studio to create button event to read text file? i know about streamReader and if i declare wchich exacly file i want to read, but if i want to choose from list of files wchich i want to display. i did research on the Internet but i didint find an answer. I know i can use isolatedStorage to read music, video, image but not text files, on the app i created few files with text in it and i want users to have posibility to display one from this file, whichever they want to see. So, can you tell me how to do this?
You can use IsolatedStorage to read any file type you wish. You must of been using something like a Launcher that filters out the file type based on the Chooser.
You can open a file like this:
private async Task<string> ReadTextFile(string file_name)
{
// return buffer
string file_content = "";
// Get the local folder
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the file
StorageFile file;
try
{
file = await local.GetFileAsync(file_name);
}
catch (Exception ex)
{
// no file, return empty
return file_content;
}
// Get the stream
System.IO.Stream file_stream = await file.OpenStreamForReadAsync();
// Read the data
using (StreamReader streamReader = new StreamReader(file_stream))
{
file_content = streamReader.ReadToEnd(); // read the full text file
streamReader.Close();
}
// Close the stream
file_stream.Close();
}
// return
return file_content;
}
If you want to get the PackageLocation (files that you added into the project like assets and images) then replace the LocalFolder with
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
With Windows Phone 8.1, File Pickers are allowed, consisting the same functionality you are expecting, so probably you might want to upgrade your app to WP8.1.
Here's more info on this API : Working with File Pickers

Windows Phone 8 - Saving Microphone File as .wav

I am using following method to save a recording of microphone in WP8 to a file:
private void SaveToIsolatedStorage()
{
// first, we grab the current apps isolated storage handle
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
// we give our file a filename
string strSaveName = "myFile.wav";
// if that file exists...
if (isf.FileExists(strSaveName))
{
// then delete it
isf.DeleteFile(strSaveName);
}
// now we set up an isolated storage stream to point to store our data
IsolatedStorageFileStream isfStream =
new IsolatedStorageFileStream(strSaveName,
FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
// ok, done with isolated storage... so close it
isfStream.Close();
}
The file is saved. However, I do not know where does it save it, and how can I access it.
I wish to permanently save it to the device so I can access it from outside the app (Let's say from a file explorer app, or from the music player app).
Thanks
Use this code to get saved file name from isolated storage and use this to read this file from stored loacation:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
String[] filenames=myIsolatedStorage.GetFileNames();

How to save IBuffer to IStorageFile on WP8?

There is Windows.Storage.FileIO.WriteBufferAsync method, but it's not supported on WP8. What's the right way to save a buffer to a storage file on a phone?
You have a couple options as to how you can proceed here. However, the extensions you'll need to make working with IBuffer objects easier are all located in the System.Runtime.InteropServices.WindowsRuntime namespace. You may also need the System.IO namespace for the OpenStreamForWriteAsync extension.
private async void SaveBuffer(Windows.Storage.Streams.IBuffer myBuffer)
{
Windows.Storage.StorageFile myFile = await Windows.Storage.StorageFile.GetFileFromPathAsync("...");
using (var writeStream = await myFile.OpenStreamForWriteAsync())
{
// Option 1: Cast to stream and copy
myBuffer.AsStream().CopyTo(writeStream);
// Option 2: Cast to byte array and write
var content = myBuffer.ToArray();
writeStream.Write(content, 0, content.Length);
}
}
Ref:
IBuffer.AsStream Extension
IBuffer.ToArray Extension

Debugging WP8 Native Code using a file

I'm developing a WP8 app that has some native code (runtime component).
Inside the runtime component I need to check to content of a c style array.
Because this array is not small, I thought the best I could do is write the array in a file
using fopen/fwrite/fclose;
Checking the returned value from fopen and fwrite, I can see that it succeeded.
But I cannot find the file (using Windows Phone Power Tools).
So where has the file been written?
Is there another way to dump the content of the array to a file (on the computer) from visual studio ?
I'm unfamiliar with the fopen/fwrite/fclose APIs in WP8. Which probably means it's not a whitelisted API you can use to submit your app with. It's best if you just use "Windows::Storage::ApplicationData::Current->LocalFolder" when working with IsoStore in C++. See Win8 code sample # http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700361.aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1
Thanks Justin,
here's how I ended up doing it:
auto folder = Windows::Storage::ApplicationData::Current->LocalFolder;
Concurrency::task<Windows::Storage::StorageFile^> createFileOp(
folder->CreateFileAsync(L"Data.bin", Windows::Storage::CreationCollisionOption::ReplaceExisting));
createFileOp.then(
[nData, pData](Windows::Storage::StorageFile^ file)
{
return file->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
})
.then([nData, pData](Windows::Storage::Streams::IRandomAccessStream^ stream)
{
auto buffer = ref new Platform::Array<BYTE>(pData, nData);
auto outputStream = stream->GetOutputStreamAt(0);
auto dataWriter = ref new Windows::Storage::Streams::DataWriter(outputStream);
dataWriter->WriteBytes(buffer);
return dataWriter->StoreAsync();
})
.wait();
Now compare that to what I "meant" :
FILE *fp = fopen("Data.bin", "wb");
if (fp)
{
int ret = fwrite(pData, 1, nData, fp);
fclose(fp);
}