Convert StorageFile to string - c#

We need to store an image file as a string in a UWP app. This was the plan:
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
byte[] fileBytes = File.ReadAllBytes(file.Path);
string fileString = Convert.ToBase64String(fileBytes);
but the line
byte[] fileBytes = File.ReadAllBytes(file.Path);
throws
System.UnauthorizedAccessException Access to the path 'C:\MyFolder\ImageFile.png' is denied.
For this exercise Everyone has Full Control permission on the file. I've also moved the file to various locations including a USB stick but always get the same exception. I assume this is a UWP thing rather than a permissions thing?
How do we save an image file as a string in a UWP app?

You get the exception, because in UWP you only can access to files over the path, is in the App-Package area.
To solve your problem you can use the IBuffer extension ToArray:
IBuffer buffer = await FileIO.ReadBufferAsync(file);
string fileString = Convert.ToBase64String(buffer.ToArray());

you can't directly access to a file with string path. In UWP, you should always access file with Storage(File, Folder)check this
to get Bytes, you can use FileIO class or Open Stream with StorageFile.

Related

Access file from the app folder in uwp

Directory:
App1
- MainPage.xaml.cs
- Sample.xaml
im trying to do is getting the xaml content from the sample as a string but it doesnt work since it cant find the file:
var x = Path.GetFullPath(#"sample.xaml");
FileStream s = new FileStream(x, FileMode.Open);
How can I fix this?
I haven't tried this give it a try.
Save your file in a location eg (Assets Folder)Now, make sure that the
build action is set to Content.
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/youfile.xaml"));
The StorageFile you get is of course read-only, but it can be passed to any API that expects a StorageFile.
If you want to read you can try.
var result = storageFile.OpenReadAsync()
StorageFile Documentation
The source files (.xaml, .cs) are compiled, and in the deployed app they do not exist as physical files, so you can't open them this way.

Windows Phone 8.1 access file in Documents folder

I'm new to windows phone development, and not using silverlight or WPF. I copy the file "links.txt" into my Windows Phone folder at "\Documents\" and I want to access and get the content in the file, but I'm getting back as access denied error. I click on Package.appxmanifest file then select "Capabilities" tab, but I don't see "Documents Library Access" for me to check it. As matter fact I don't see any "... Library Access" showing. Below is the code:
string fileName = "\\Documents\\links.txt";
string parentPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(parentPath, fileName);
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
Any suggestion how can I read the file? thanks.
Updates:
It seems the code above does not work, but when using the code below and change the folder to "Music" instead of "Documents" then check the Capabilities for "MusicLibrary", it's working.
var folder = KnownFolders.MusicLibrary;
var file = await folder.GetFileAsync("links.txt");
var read = await FileIO.ReadTextAsync(file);
Thanks!
You are give the wrong filePath actual path is in this image
i try your code it shows same error so correct your file path
If you checked need Capability for Documents you should use KnownFolders class instead ApplicationData.Current.LocalFolder.Path.
For example:
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile file = await storageFolder.CreateFileAsync("sample.dat", CreationCollisionOption.ReplaceExisting);

W10 UWP - Set remote image as desktop wallpaper / lockscreen

I'm trying to set a remote image as the desktop wallpaper / phone lockscreen in my W10 UWP app:
string name = "test_image.jpg";
Uri uri = new Uri("http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg");
// download image from uri into temp storagefile
var file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri));
// file is readonly, copy to a new location to remove restrictions
var file2 = await file.CopyAsync(KnownFolders.PicturesLibrary);
// test -- WORKS!
//var file3 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Design/1.jpg"));
// try set lockscreen/wallpaper
if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // Phone
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file2);
else // PC
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file2);
file1 doesn't work as it is read-only, so I copy it to a new location (pictures library) to remove restrictions -> file2.
Note: file3 works, so I'm not sure what's happening -- I assume TrySetWallpaperImageAsync/TrySetLockScreenImageAsync only accepts msappx local files...
Anyone have any ideas on work arounds?
Thanks.
Save your remote image to ApplicationData.Current.LocalFolder first, then use TrySetWallpaperImageAsync/TrySetLockScreenImageAsync and point to the saved image instead of directly referencing the remote image should work.

Save changes in file in Windows Store app in required directory

using c#, VS2013, windows store app
In simple program have a file with some data saved in JSON format. I'll try to add new data to this file and then store it.
Try to save file in JSON with next code:
string result = await JsonConvert.SerializeObjectAsync(groups);
//get file path
string pathOfFile = Path.GetDirectoryName(file.Path); //get path
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(pathOfFile); //create dir by path
StringBuilder builder = new StringBuilder();
builder.Append(folder.Path);
builder.Append("\\EventsData.json");
Uri uriToSave = new Uri(builder.ToString());
//create file
StorageFile fileToWrite =
await StorageFile.GetFileFromApplicationUriAsync(uriToSave);
using (IRandomAccessStream stream =
await file.OpenAsync(FileAccessMode.ReadWrite))
{
// write the JSON file
using (DataWriter textWriter = new DataWriter(stream))
{
textWriter.WriteString(result);
await textWriter.StoreAsync();
}
}
But during executing code StorageFile fileToWrite = await StorageFile.GetFileFromApplicationUriAsync(uriToSave); got exception System.ArgumentException
During debagging got next Uri
Question - why i got such exception and if I'm wrong - how to save file in windows store app in required directory?
Also look MSDN sample for writing data to file, and use code like in tutorial but got System.UnauthorizedAccessException:
StorageFile sampleFile = await folder.CreateFileAsync("EventsData.json", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);
Why Access denied or I missing something?
You cannot write to the install directory without explicit permission from the user.
Here is the protocol instead:
At first startup, check to see if there is a file in the local data folder (ApplicationDataContainer), if not, read in the file from the install directory.
Write out a copy of the file to the local app data folder (Check out guides on ApplicationDataContainer for more info there)
Edit this file freely.

Can't use file stream obtained from skydrive to create BitmapImage

I'm writing a windows phone 8 app and I would like to let users use images saved to their skydrive in my app. The piece of code I'm having trouble with (I believe) is below.
StorageFile thefile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("b4b.png", CreationCollisionOption.ReplaceExisting);
Uri theuri = new Uri("ms-appdata:///local/b4b.png");
var thething = await client.BackgroundDownloadAsync(filepath, theuri); <--- line where program crashes
BitmapImage src = new BitmapImage();
src.SetSource((Stream)await thefile.OpenReadAsync());
WriteableBitmap image = new WriteableBitmap(src);
all the signing in and authentication stuff that the user needs to do is already done by this point and works as expected. When my program reaches the marked line, it suddenly crashes. The errors I receive are...
A first chance exception of type 'System.ArgumentException' occurred in Microsoft.Live.DLL
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded 'C:\windows\system32\en-US\mscorlib.debug.resources.dll'. Module was built without symbols.
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.ni.dll
Does anyone know how to fix this?
I inserted breakpoints to trace the program and it appears that the storage file is being made and the uri is correct, but when I try to download the file to it, the program gives me the error. I confirmed the filepath for the file on skydrive is also correct. If I try to use DownloadAsync() instead it appears to work but then the program crashes when I try to use the stream obtained from the skydrive file instead and gives the same error.
Any ideas? Because I can't figure out what could be wrong.
The file being downloaded is a png image.
EDIT: Solution Found
After some more research I found out that when you download files from skydrive a call for a files id...
filepath = result.id;
as above that does not give you the contents of the file. I didn't check what it was obtaining but I'd assume it was probably the metadata. To obtain the actual contents of the file you must add "/contents".
The correct path would then be
filepath = result.id + "/contents";
I edited my code as shown below and it now works perfectly.
StorageFile thefile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("b4b.png", CreationCollisionOption.ReplaceExisting);
Uri theuri = new Uri("ms-appdata:///local/b4b.png", UriKind.Absolute);
var thething = await client.DownloadAsync(filepath + "/content");
Stream stream = thething.Stream;
stream.Seek(0, SeekOrigin.Begin);
BitmapImage src = new BitmapImage();
src.SetSource(stream);
Hope this helps anyone having the same problem as I was!
From the #deboxturtle's update, as an answer for search sake:
After some more research I found out that when you download files from skydrive a call for a files id...
filepath = result.id;
as above that does not give you the contents of the file, you get file metadata as json. To obtain the actual contents of the file you must add /content to the id.
The correct path would then be
filepath = result.id + "/content";
I edited my code as shown below and it now works perfectly.
var filepath = result.id + "/content";
StorageFile thefile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"b4b.png", CreationCollisionOption.ReplaceExisting);
var thething = await client.DownloadAsync(filepath);
Stream stream = thething.Stream;
stream.Seek(0, SeekOrigin.Begin);
BitmapImage src = new BitmapImage();
src.SetSource(stream);

Categories

Resources