Where do I find the location of the folders and text files I created in windows phone 8. Can we see it in the explorer like we search for the app data in Windows 8? I'm not using IsolatedStorage, instead Windows.Storage. I want to check if the folders and files are created as I want.
This is how I write the file
IStorageFolder dataFolder = await m_localfolder.CreateFolderAsync(App.ALL_PAGE_FOLDER, CreationCollisionOption.OpenIfExists);
StorageFile PageConfig = null;
try
{
PageConfig = await dataFolder.CreateFileAsync("PageConfig.txt", CreationCollisionOption.OpenIfExists);
}
catch (FileNotFoundException)
{
return false;
}
EDIT
try
{
if (PageConfig != null)
{
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
DataWriter writer = new DataWriter(stream.AsOutputStream());
writer.WriteString(jsonString);
}
}
}
catch (Exception e)
{
string txt = e.Message;
return false;
}
And this is how I read the file from the folder
try
{
var dataFolder = await m_localfolder.GetFolderAsync(App.ALL_PAGE_FOLDER);
var retpng = await dataFolder.OpenStreamForReadAsync("PageConfig.txt");
if (retpng != null)
{
try
{
using (StreamReader streamReader = new StreamReader(retpng))
{
jsonString = streamReader.ReadToEnd();
}
return jsonString;
}
catch (Exception)
{
}
}
}
catch (FileNotFoundException)
{
}
There are also other folders created. I dont receive any exceptions while writing but when I read the string is empty.
Windows.Storage.ApplicationData.LocalFolder(MSDN link here) is another name for Isolated Storage that is in Windows.Storage namespace. The only other location you can access is your app's install directory (and only read-only).
You can use Windows Phone Power Tools to browse what files are in your app's Isolated Storage, or the command line tool that comes with the SDK.
With the help of Windows Phone Power tools, I figured out that there was no text being written in file.
So I converted string to byte and then wrote it to the file and it works! Don't know why the other one does not work though..
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
stream.Write(fileBytes, 0, fileBytes.Length);
}
The command line tool that comes with Windows Phone SDK 8.0 is Isolated Storage Explorer (ISETool.exe) which reside in "Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageExplorerTool" folder for default installation
ISETool.exe is used to view and manage the contents of the local folder
Related
This is how i read my textfile in android.
#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
WWW reader = new WWW(full_path);
while (!reader.isDone){}
json = reader.text;
// PK Debug 2017.12.11
Debug.Log(json);
#endif
and this is how i read my textfile from pc.
#if UNITY_STANDALONE
string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
StreamReader reader = new StreamReader(full_path);
json = reader.ReadToEnd().Trim();
reader.Close();
#endif
Now my problem is that i don't know how to write the file on mobile cause i do it like this on the standalone
#if UNITY_STANDALONE
StreamWriter writer = new StreamWriter(path, false);
writer.WriteLine(json);
writer.Close();
#endif
Help anyone
UPDATED QUESTION
This is the json file that it is in my streamingasset folder that i need to get
Now my problem is that i don't know how to write the file on mobile
cause I do it like this on the standalone
You can't save to this location. Application.streamingAssetsPath is read-only. It doesn't matter if it works on the Editor or not. It is read only and cannot be used to load data.
Reading data from the StreamingAssets:
IEnumerator loadStreamingAsset(string fileName)
{
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);
string result;
if (filePath.Contains("://") || filePath.Contains(":///"))
{
WWW www = new WWW(filePath);
yield return www;
result = www.text;
}
else
{
result = System.IO.File.ReadAllText(filePath);
}
Debug.Log("Loaded file: " + result);
}
Usage:
Let's load your "datacenter.json" file from your screenshot:
void Start()
{
StartCoroutine(loadStreamingAsset("datacenter.json"));
}
Saving Data:
The path to save a data that works on all platform is Application.persistentDataPath. Make sure to create a folder inside that path before saving data to it. The StreamReader in your question can be used to read or write to this path.
Saving to the Application.persistentDataPath path:
Use File.WriteAllBytes
Reading from the Application.persistentDataPath path
Use File.ReadAllBytes.
See this post for a complete example of how to save data in Unity.
This is the way I do it without the WWW class (works for Android an iOS), hope its useful
public void WriteDataToFile(string jsonString)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
File.WriteAllText(filePath, jsonString);
}
else
{
File.WriteAllText(filePath, jsonString);
}
}
I have an UWP application, In that I need to run the MSI file on the button click.
I don't think UWP will support "process.start(filename)". Is it possible in UWP to achieve this?.
The UWP cant open MSI.
But uwp can open the other type file.
You can use Launcher.
Pick the msi that you want run.
Run msi by launcher file.
The result is always failed.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//pick msi file
FileOpenPicker pick = new FileOpenPicker();
pick.FileTypeFilter.Add(".msi");
StorageFile file = await pick.PickSingleFileAsync();
//run
bool result = await Launcher.LaunchFileAsync(file);
if (result)
{
//success
}
}
But you will see the result is false ,because Many file types that contain executable code, for example .exe, .msi, and .js files, are blocked from launching
You can open the folder and make the use to click the msi file.The code is:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//pick msi file
var pick = new FileOpenPicker();
pick.FileTypeFilter.Add(".msi");
var file = await pick.PickSingleFileAsync();
//run
var result = await Launcher.LaunchFileAsync(file, new LauncherOptions
{
TreatAsUntrusted = true,
DisplayApplicationPicker = true
});
if (result)
{
//success
}
else
{
//alway failed
var folder = await file.GetParentAsync();
if (folder != null)
{
await Launcher.LaunchFolderAsync(
folder, //if you can get the file's parent
new FolderLauncherOptions
{
ItemsToSelect = {file}
});
}
}
}
See:Windows Store App running .msi installer
https://msdn.microsoft.com/en-us/library/windows/apps/hh701471.aspx?f=255&MSPPError=-2147217396
I am using this code to let users to choose where to save a file:
var fileSavePicker = new FileSavePicker();
fileSavePicker.FileTypeChoices.Add("Pdf", new List<string>(){".pdf"});
fileSavePicker.SuggestedFileName = $"{pdfFile.Name}";
fileSavePicker.SuggestedSaveFile = pdfFile;
fileSavePicker.PickSaveFileAndContinue();
This code works fine on Windows Phone 8.1 but give me an exception (System.UnauthorizedAccessException) when running on Windows 10 mobile. How can I solve this?
When I use FileSavePicker.PickSaveFileAndContinue method in the visual, there is an error “ The FileSavePicker.PickSaveFileAndContinue() is obsolete: instead, use PickSaveFileAsync() ”. So you can use FileSavePicker.PickSaveFileAsync() method in Windows 10 mobile.
Update:
I have test Windows Phone 8.1 on Windows 10 Mobile, it was ok. The code of my project below , you can refer to.
You can also refer to this sample about FileSavePicker.
private void SaveFileButton_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
OutputTextBlock.Text = "";
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
}
/// <summary>
/// Handle the returned file from file picker
/// This method is triggered by ContinuationManager based on ActivationKind
/// </summary>
/// <param name="args">File save picker continuation activation argment. It cantains the file user selected with file save picker </param>
public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
OutputTextBlock.Text = "File " + file.Name + " was saved.";
}
else
{
OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
I have a spec in which there is a need to ignore HTTPS certificates and also to get the status of Upload/Download.
I am using HttpClient to ignore the certificate but i could not find the way to get the status of downloading/Uploading.
I know it was there in WebClient Windows Phone 8 and Webclient not there in Windows 8.1.
So please guide me to accomplish both these things.
For Download progress, You can return response stream from your Http request and can use below code to write to file which also display progress status
IInputStream inputStream = null;
IRandomAccessStream fs = null;
try
{
inputStream = responseStream.AsInputStream();
ulong totalBytesRead = 0;
fs = await file.OpenAsync(FileAccessMode.ReadWrite);
ulong fileSize = Convert.ToUInt64(Size);
while (true)
{
// Read from the web.
if (!cancellationToken.IsCancellationRequested)
{
IBuffer buffer = new Windows.Storage.Streams.Buffer(512);
buffer = await inputStream.ReadAsync(
buffer,
buffer.Capacity,
InputStreamOptions.None);
if (buffer.Length == 0)
{
// There is nothing else to read.
break;
}
// Report progress.
totalBytesRead += buffer.Length;
double progress = ((double)totalBytesRead / fileSize);
double Value = progress * 100;
System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);
await fs.WriteAsync(buffer);
}
else
{
inputStream.Dispose();
fs.Dispose();
await file.DeleteAsync();
break;
}
}
inputStream.Dispose();
fs.Dispose();
}
catch
{
}
For upload Progress, there is no in built support to do that, but you can use
ProgressMessageHandler found in System.Net.Http.Handler which you can found on Nuget and than hook that to your HttpClient Object.
I am not able to use DownloadDataAsync method.The only option present is DownloadStringAsync method.How can I download a zip file using this method.(I am new to windows phone 8 app development)
I just thought to share the solution that worked for me.
I created a web request to the url given and downloaded the gzip file into isolated storage file.Now after downloading i created a destination file stream and stored the compressed gzip stream file from source file to destination file using WriteByte method of GZipStream.Now we get uncompressed file.
Note:-GZipStream can be added to Visual studio from NuGet manager.
Here is the code snippet which i used to download and extract GZip file.
public async Task DownloadZipFile(Uri fileAdress, string fileName)
{
try
{
WebRequest request = WebRequest.Create(fileAdress);
if (request != null)
{
WebResponse webResponse = await request.GetResponseAsync();
if (webResponse.ContentLength != 0)
{
using (Stream response = webResponse.GetResponseStream())
{
if (response.Length != 0)
{
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
using (IsolatedStorageFileStream file = isolatedStorage.CreateFile(fileName))
{
const int BUFFER_SIZE = 100 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread;
while ((bytesread = await response.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
file.Write(buf, 0, bytesread);
}
file.Close();
FileStream sourceFileStream = File.OpenRead(file.Name);
FileStream destFileStream = File.Create(AppResources.OpenZipFileName);
GZipStream decompressingStream = new GZipStream(sourceFileStream, CompressionMode.Decompress);
int byteRead;
while ((byteRead = decompressingStream.ReadByte()) != -1)
{
destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
PhoneApplicationService.Current.State["DestinationFilePath"] = destFileStream.Name;
}
}
FileDownload = true;
}
}
}
}
if (FileDownload == true)
{
return DownloadStatus.Ok;
}
else
{
return DownloadStatus.Other;
}
}
catch (Exception exc)
{
return DownloadStatus.Other;
}
}
Do you must use DownloadStrringAsync method? otherwise you can check these:
How to extract zipped file received from HttpWebResponse?
download and decompress a zip file in windows phone 8 application
Extract zip file from isolatedstorage
How to download a GZIP file from web to Windows Phone 7 and unzip the contents
To download zip file from the url first there is need to store zip files into isolated storage and after that extract it and read the file as per requirement.
http://axilis.hr/uznip-archives-windows-phone