I have a problem while reading a file in C#. Here's the code:
protected override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image();
IMG.Loaded = IMG_Loaded;
string FP = FArgs.Files[0].Path;
Uri = FP;
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));
FV.Items.Add(IMG);
PathBlock.Text = FArgs.Files[0].Name " - Ivirius Image Viewer";
void IMG_Loaded(object sender, RoutedEventArgs e)
{
IMG.Source = new BitmapImage(new Uri(Uri));
}
}
}
if (Args == null)
{
PathBlock.Text = "Ivirius Image Viewer";
}
}
The problem is at this part:
IMG.Source = new BitmapImage(new Uri(FP, UriKind.RelativeOrAbsolute));
The image won't load, even after trying a resource that the app CAN access in its own files:
IMG.Source = new BitmapImage(new Uri("ms-appx:///09.png, UriKind.RelativeOrAbsolute));
It still won't work. This only works with this code:
var FOP = new Windows.Storage.Pickers.FileOpenPicker();
StorageFile F = await FOP.PickSingleFileAsync();
IRandomAccessStream FS = await F.OpenAsync(FileAccessMode.Read);
var BI = new BitmapImage();
var IMG = new Image();
await BI.SetSourceAsync(FS);
IMG.Source = BI;
Sadly, I can't use a file stream OR a file picker in the first code example, so I can't make it work as I did here.
CodePudding user response:
Image.Source = new BitmapImage(); doesn't work in UWP
The problem is file Path
property does not use to set image source directly in UWP platform.
Derive from your code, it looks you open the image file with current app, if you can get the IStorageItem
from FArgs.Files
list, you could also convert it as StorageFile
, and then pass the opened file stream to BitmapImage
.
For more detail steps please refer to the following code.
protected async override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
var FArgs = Args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
if (Args != null)
{
if (Args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
{
var IMG = new Image();
string FP = FArgs.Files[0].Path;
var Uri = FP;
StorageFile imageFile = FArgs.Files[0] as StorageFile;
using (var stream = await imageFile.OpenReadAsync())
{
var bitmp = new BitmapImage();
bitmp.SetSource(stream);
IMG.Loaded = (s, e) => { IMG.Source = bitmp; };
}
RootLayout.Children.Add(IMG);
}
}
if (Args == null)
{
}
}