Access to the path, when try to ReadAllTheBytes [duplicate] - c#

This question already has an answer here:
UWP, Access to the path is denied
(1 answer)
Closed 3 years ago.
I am getting a file, via a picker and I am displaying that image in a Image control in xaml.
The image displays perfectly, but when I tried to convert the path to bytes, I get the error
Tried to give picture library permition
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpeg");
var file = await picker.PickSingleFileAsync();
if (file != null) {
var stream = await file.OpenReadAsync();
var bitmap = new BitmapImage();
bitmap.SetSource(stream);
var bytes = File.ReadAllBytes(file.Path); // Error
selectedimage.Source = bitmap;
{"Access to the path 'some path' is denied."}

Access to the path, when try to ReadAllTheBytes
UWP run in sandbox, we can't access the file with the path directly,Even though we already add broadFileSystemAccess capability, we could not use ReadAllTheBytes under System.IO namespace. And Pavel Anikhouski's comment is correct, we could use MemoryStream to convert the file to bytes.
byte[] result;
using (Stream stream = await imageFile.OpenStreamForReadAsync())
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}

Related

how to get Bytes of a file for sending in UWP?

I'm a newbie in UWP and i want to open a file of any type and transmit the bytes of it to the reciever. forexample for a jpg file i wrote this code:
// Create FileOpenPicker instance
FileOpenPicker fileOpenPicker = new FileOpenPicker();
// Set SuggestedStartLocation
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
// Set ViewMode
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
fileOpenPicker.FileTypeFilter.Clear();
fileOpenPicker.FileTypeFilter.Add(".jpg");
// Open FileOpenPicker
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
the two last lines are for writing the bytes into a file supposing in the receiver. However i keep getting the following exception:
System.InvalidOperationException: 'Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.'
Try this Code.
try {
FileOpenPicker openPicker = new FileOpenPicker {
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png" }
};
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null) {
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) {
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
var LoadReader = await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
}
}
} catch (Exception ex) {
}
consider wrapping last operation in Task.Run()
await Task.Run(()=>{
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
});
You should directly read the bytes from the StorageFile returned from your FilePicker, lest you end up with File permission errors in the future.
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
var buffer = await FileIO.ReadBufferAsync(file);
byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer);
You should also use await FileIO.WriteBytesAsync(targetFile, myBytes) to write.
Unless you have broadFileSystemAccess in your package Manifest, you should generally avoid using the System.IO API unless you know your application explicitly has permission to access files in that area (i.e., your application's local storage), and instead use Windows.Storage API's
Check MSDN for File Access Permissions for UWP apps for more information on file permissions.
And if you do use System.IO, always perform the work on the background thread via await Task.Run(() => { ... }

xamarin.forms save file/image

coding xamarin form project and also using pcl storage. have problem with saving image or file on device all examples i found show how to save stream of byte array into file but non of them show how to turn convert image into usable format for saving.
var webImage = new Image();
webImage.Source = new UriImageSource
{
CachingEnabled = false,
Uri = new Uri("http://server.com/image.jpg"),
};
byte[] image = ????(what i need)????(webImage.Source);
// get hold of the file system
IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
// populate the file with image data
using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
stream.Write(image, 0, image.Length);
}
In other words looking for code to save image/file on device from url.
Tried ffimageloading since it contain converter to byte[], but always get error:"Object reference not set to an instance of an object." for GetImageAsJpgAsync and GetImageAsPngAsync method. problem might be that image isn't fully loaded. but finish event and finish command never get called even trough image is fully loaded on screen and bound to cachedImage.
var cachedImage = new CachedImage()
{
Source = "https://something.jpg",
FinishCommand = new Command(async () => await TEST()),
};
cachedImage.Finish += CachedImage_Finish;
var image = await cachedImage.GetImageAsJpgAsync();
With FFImageLoading (I noticed you use it):
await ImageService.Instance.LoadUrl("https://something.jpg").AsJpegStream();
If you want to get original file location, use this:
await ImageService.Instance.LoadUrl("https://something.jpg").Success((imageInfo) => { //TODO imageInfo.FilePath } ).DownloadOnly();

"File-name" has been damaged : Windows Phone 8.1

I am launching document from isolated storage, when I debug on next code, previous stream gets closed and getting this exception.
"File-Name" has been damaged and can't be opened.
See my code below:
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (stream = storageFile.OpenFile("Document.docx", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync("Document.docx");
await Windows.System.Launcher.LaunchFileAsync(pdffile);
1) Make Sure If you are Downloading file from the URI than you should use WebClient instead of HttpWebRequest
2) Make sure you paas the correct URI

Copy or open external file in windows RT app

I would like to show a pdf from a website in my windows rt app (for Desktops with windows 8). How can I handle this?
If I add the file manually to the asset I can display it. But how can I do this with files where are not located on my asset Folder?
Can I copy the file to the StorageFolder?
Or can I directly open the file from the website?
Please give me some hints how I can solve this.
THX
To open files from you application you use Launcher in Windows 8 Applications. Refer the MSDN LINK: http://msdn.microsoft.com/en-in/library/windows/apps/hh701465.aspx and http://www.codeguru.com/win_mobile/win_store_apps/launching-files-with-associated-programs-in-windows-8.x-and-vb.htm
Hi I want to open it in my app and I not want to use the launcher.
I copy the file with HttpWebRequest to LocalFolder and process the pdf. I've solved it this way:
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);
//TODO Systemuser
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var response = await request.GetResponseAsync();
List<Byte> allBytes = new List<byte>();
using (Stream imageStream = response.GetResponseStream()) {
byte[] buffer = new byte[4000];
int bytesRead = 0;
while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0) {
allBytes.AddRange(buffer.Take(bytesRead));
}
}
file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, allBytes.ToArray());
await RenderPDFPage(fileName);

Taking a Picture, and saving it to Disk in a Windows 8 Metro-style App

I am ABLE to take a picture, but I am having trouble saving it to one of the KnownFolders.
Yes, I have declared the Picture Library Access Capability in Package.appxmanifest.
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
StorageFile file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
var stream = await file.OpenAsync(FileAccessMode.Read);
var bitmap = new BitmapImage();
bitmap.SetSource(stream);
Photo.Source = bitmap;
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
var result = await file.CopyAsync(storageFolder, "tps.jpg");
}
The code stops on the last line. What am I doing wrong?
I think you also need declare the file types!
In the Declarations tab, choose File Type Associations from Available
Declarations and click Add.
Under Properties, set the Name property to image.
In the Supported File Types box, add .jpg as a supported file type by
entering .jpg in the FileType field.

Categories