Windows Phone 8 choose text file C# - windows-phone-8

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

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

Reading a project text file windows phone 8

I'm having trouble accessing a text file that is packaged with my Windows Phone 8 app.
Here is the code:
var ResrouceStream = Application.GetResourceStream(new Uri("Data-Test.docx", UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
// logiic here
retrun "Hi";
}
}
else
{
return "hello";
}
Seems simple but the app always returns "hello". i have placed the file in root and also in assets, changed it to content - copy and do not copy, resource copy and do not copy but always it returns "hello".
Spent several hours on this and all solutions I can find show the solution or very similar above!
What am I doing wrong?
EDIT: Returns "hello" when I deploy to phone or emulator.
also tried "/Data-Test...", #"\Data-Text..., #/"Data-Test...!
UPDATE 1:
string aReturn = "";
var asm = Assembly.GetExecutingAssembly();
//Use this to verify the namespacing of the "Embedded Resource".
//asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var ResourceStream = asm.GetManifestResourceStream("ContosoSocial.Assets.QuizQuestions.QuizQuestions-Test1.docx");
if (ResourceStream != null) // <--CHECKED AND DOES NOT EQUAL NULL
{
Stream myFileStream = ResourceStream;
if (myFileStream.CanRead) // <-- CHEACKED AND CAN READ
{
StreamReader myStreamReader = new StreamReader(myFileStream);
LOGIC & EXCEPTION HERE...?
string myLine = myStreamReader.ReadLine();
}
else
{
aReturn = "myFileStream.CanRead = true";
}
}
else
{
aReturn = "stream equals null";
}
Debug.WriteLine(aReturn);
}
The assignment of myFileStream to a StreamReader object is throwing the exception null pointer. I thought I would wrap myFileStream to a StreamReader so I can read a line at a time..? This is my first c# project and I'm unfamiliar with it's syntax and classes.
UPDATE 2:
OK I added...
Debug.WriteLine(aReturn);
...following...
string myLine = myStreamReader.ReadLine();
...and noticed it was retrieving only the 2 characters 'PK' !
So saved the .docx file as .txt and reinserted adn changed build copy to embedded - do not copy...Happy days it now pulls off the first line in the file.
Thanks to OmegaMan for your help with this one :-)
Change file type in the project to Embedded Resource
Extract the resource by working the namespace to its location. Here is an example code where I pull in an XSD:
Code:
var asm = Assembly.GetExecutingAssembly();
// Use this to verify the namespacing of the "Embedded Resource".
// asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var f1 = asm.GetManifestResourceStream("UnitTests.Resources.NexusResponse.xsd");
Note this is not tested on WP8, but GetExecutingAssembly is stated to work within .Net. If you get the namespace wrong, uncomment out the code and display or debug to determine the resources and their namespace.

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

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