How to save IBuffer to IStorageFile on WP8? - windows-phone-8

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

Related

converting a file path to a URI

When using the secondaryTitle in c++, I have to enter a URI that points to the logo. The URI fails if I try to point it to any file outside of the app's package. What I tried to is have the user select the file using a filepicker
void App3::MainPage::FindLogo(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->ViewMode = PickerViewMode::Thumbnail;
openPicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
openPicker->FileTypeFilter->Append(".jpg");
openPicker->FileTypeFilter->Append(".jpeg");
openPicker->FileTypeFilter->Append(".png");
create_task(openPicker->PickSingleFileAsync()).then([this](Windows::Storage::StorageFile^ file)
{
if (file)
{
StorageFolder^ folder;
auto ur = ref new Uri("ms-appx:///Assets//");
String^ s = Windows::ApplicationModel::Package::Current->InstalledLocation->Path;
create_task(StorageFolder::GetFolderFromPathAsync(s)).then([=](StorageFolder^ folder){
create_task(file->CopyAsync(folder, file->Name, NameCollisionOption::ReplaceExisting)).then([this, file](task<StorageFile^> task)
{
logoFile = ref new Uri("ms-appdata:///local//App3//Assets//StoreLogo.scale-100.png");
});
});
}
});
}
then copy that file and save it in the app directory. It still fails when using a uri to point to the new copy.
void App3::MainPage::kk(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
text = url->Text->ToString();
ids = id->Text->ToString();
auto test = ref new Windows::UI::StartScreen::SecondaryTile(ids, "hi", text, logoFile, Windows::UI::StartScreen::TileSize::Square150x150); // Breaks right here
// error: logofile is 0x05fcc1d0
num++;
test->RequestCreateAsync();
//auto uri = ref new Windows::Foundation::Uri("http://www.google.com");
//concurrency::task<bool> launchUriOperation(Windows::System::Launcher::LaunchUriAsync(uri));
}
UPDATED
create_task(openPicker->PickSingleFileAsync()).then([this](Windows::Storage::StorageFile^ file)
{
if (file)
{
StorageFolder^ folder = ApplicationData::Current->LocalFolder;
create_task(file->CopyAsync(folder, file->Name, NameCollisionOption::ReplaceExisting)).then([this, file](task<StorageFile^> task)
{
String^ path = "ms-appdata:///local/" + file->Name;
logoFile = ref new Uri(path);
});
}
});
You're attempting to copy the picked file into the app package location (InstalledLocation), rather than into an app data folder. The package location is read-only, so CopyAsync should be failing. Use StorageFolder^ localFolder = ApplicationData::Current->LocalFolder; instead.
Also, you do need the /// in ms-appdata:///local because it's a shorthand to omit the package id, but you need only a single / elsewhere in the URI.
Finally, be aware that tile images must be 200KB or smaller and 1024x1024 or smaller, or they won't appear at all. If you're using photographic images, use a JPEG compression; vector images compress best with PNG. For more on dealing with this, see Chapter 16 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, specifically "Basic Tile Updates" starting on page 887 and the sidebar on page 899. The content is applicable to apps written in all languages, and it's a free book so there's no risk.

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 download then unzip to isolated storage

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)?

Best Way to keep Settings for a WinRT App?

I'm working on a WinRT app that's actually also a game. I need to keep different information such as audio settings or player statistics somewhere in sort of a file or somehow. If it's a file, just write settings in or... ? I have an idea but I think is way too rudimentary... What is the best approach to obtain this?
Any help or suggestions are greatly appreciated!
Here are some ways to save Data in a WinRT app, the method with Settings in the name is probably what you are looking for!- just added the other ones as well,- you also can serialize data if you want to. This is working code- but don't forget to add error handling etc. It's a simple demo code :)
As for settings, you can save simple settings as key and values, and for more complex settings you can use a container. I've provided both examples here =)
public class StorageExamples
{
public async Task<string> ReadTextFileAsync(string path)
{
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.GetFileAsync(path);
return await FileIO.ReadTextAsync(file);
}
public async void WriteTotextFileAsync(string fileName, string contents)
{
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, contents);
}
public void SaveSettings(string key, string contents)
{
ApplicationData.Current.LocalSettings.Values[key] = contents;
}
public string LoadSettings(string key)
{
var settings = ApplicationData.Current.LocalSettings;
return settings.Values[key].ToString();
}
public void SaveSettingsInContainer(string user, string key, string contents)
{
var localSetting = ApplicationData.Current.LocalSettings;
localSetting.CreateContainer(user, ApplicationDataCreateDisposition.Always);
if (localSetting.Containers.ContainsKey(user))
{
localSetting.Containers[user].Values[key] = contents;
}
}
}
The MSDN has an article on using app settings in Windows Store apps.
The Windows.UI.ApplicationSettings namespace contains all the classes you need.
Provides classes that allow developers to define the app settings that appear in the settings pane of the Windows shell. The settings pane provides a consistent place for users to access app settings.
Basically these classes let you store application settings and hook them into the standard place for all application settings. Your users don't have to learn anything new, the settings will be in the expected place.

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);
}