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);
Related
I am trying to save a bitmap to the Android storage.
My code looks like this:
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(folderPath, "Pictures/profile_picture.png");
var stream = new FileStream(filePath, FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
stream.Close();
But the application enters break mode and it says:
System.IO.DirectoryNotFoundException: Could not find a part of the path.
Any help is appreciated.
Thanks in advance, Zoedingl.
"Pictures" directory is not created. So, you are getting "Could not find a part of the path" error. Change code as below or you can create directory for "Pictures" then use same code should work.
var filePath = System.IO.Path.Combine(folderPath, "profile_picture.png");
Code for creating directory
Directory.CreateDirectory(System.IO.Path.Combine(folderPath, "Pictures"));
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.
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.
I'm working on an app which loads images from a chosen folder to a gridView.
when I use SetSource to set the BitmapImage source I receive an error "insufficient memory" after loading some of the images.
when I use the constructor with a Uri path it works fine. but it will only display images from the projects directory.
StorageFolder folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(RecentToken);
StorageFile file = await folder.GetFileAsync(path);
IRandomAccessStream stream = await file.OpenReadAsync();
image = new BitmapImage(new Uri(file.Path));//loads only within project directory
image.SetSource(stream);//causes insufficient memory
stream.Dispose();
Found the solution!
I set the BitmaPimage's DecodePixelHeight to the size of the Displayed image and it works fine now!
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.