Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trying to use a FileOpenPicker while running the app as Administrator will crash the app #2504

Open
bogdan-patraucean opened this issue May 12, 2022 · 64 comments
Assignees
Labels
area-File access bug Something isn't working

Comments

@bogdan-patraucean
Copy link

bogdan-patraucean commented May 12, 2022

Describe the bug

I am trying to open a File Picker but it works only if I am not using the app in elevation mode.

I'm getting the following error:

System.Runtime.InteropServices.COMException: 'Error HRESULT E_FAIL has been returned from a call to a COM component.'

The error appears when the code tries to execute the following line of code:

var file = await picker.PickSingleFileAsync();

Steps to reproduce the bug

  1. Create a WASDK app using version 1.4.2 and .NET 7
  2. Create an extension method so you can get the Window Handle

AppWindowExtension.cs

public static IntPtr GetHandle(this Microsoft.UI.Xaml.Window window)
{
    return WinRT.Interop.WindowNative.GetWindowHandle(window);
}
  1. Make the MainWindow available outside the App class

App.xaml.cs

public static Window MainWindow { get; private set; }
  1. Use the generated Button_Click event method to open the File Picker

MainWindow.xaml.cs

var picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");

InitializeWithWindow.Initialize(picker, App.MainWindow.GetHandle());

var file = await picker.PickSingleFileAsync();
  1. Build the app and try to Run as Administrator (it's not neccesary to configure elevation, just right click on the app works)
  2. Click the button to open the File Picker
  3. The app will crash :(

Expected behavior

I would expect this basic feature of picking a file to work even if I run the app as admin.
My app has a lot of features that require elevation so getting rid of elevation is not an option for me.

Screenshots

No response

NuGet package version

1.4.2

Packaging type

Packaged (MSIX)

Windows version

Insider Build (xxxxx) (only on Windows 11)

IDE

Visual Studio 2022

Additional context

The same for FolderPicker

@Petrarca181
Copy link

I can confirm this bug. Any temporary workground for this?

@bogdan-patraucean
Copy link
Author

@Petrarca181 yes, you can use directly PInvoke with CsWin32, but it's too much overhead if you ask me.

@qianchen36
Copy link

我在WindowsAppSDK 1.1 Preview 3中使用FolderPicker时遇到了同样的问题,但是我的程序需要提升的权限
I had the same problem using FolderPicker under WindowsAppSDK 1.1 Preview 3, but my program required elevated privileges

@lukedukeus
Copy link

@Petrarca181 I had to write my own with P/Invoke as well, It's basic and blocking / non-async, but gets the job done. Mostly copied from here.

using System;
using System.Runtime.InteropServices;

namespace Namespace
{

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct OpenFileName
    {
        public int lStructSize;
        public IntPtr hwndOwner;
        public IntPtr hInstance;
        public string lpstrFilter;
        public string lpstrCustomFilter;
        public int nMaxCustFilter;
        public int nFilterIndex;
        public string lpstrFile;
        public int nMaxFile;
        public string lpstrFileTitle;
        public int nMaxFileTitle;
        public string lpstrInitialDir;
        public string lpstrTitle;
        public int Flags;
        public short nFileOffset;
        public short nFileExtension;
        public string lpstrDefExt;
        public IntPtr lCustData;
        public IntPtr lpfnHook;
        public string lpTemplateName;
        public IntPtr pvReserved;
        public int dwReserved;
        public int flagsEx;
    }
    public static class FilePicker
    {

        [DllImport("comdlg32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern bool GetOpenFileName(ref OpenFileName ofn);

        // usage: string filename = FilePicker.ShowDialog("C:\\", new string[] { "png", "jpeg", "jpg" }, "Image Files", "Select an Image File...");
        public static string ShowDialog(string startingDirectory, string[] filters, string filterName, string dialogTitle)
        {
            var ofn = new OpenFileName();
            ofn.lStructSize = Marshal.SizeOf(ofn);

            ofn.lpstrFilter = filterName;
            foreach (string filter in filters)
            {
                ofn.lpstrFilter += $"\0*.{filter}";
            }
            ofn.lpstrFile = new string(new char[256]);
            ofn.nMaxFile = ofn.lpstrFile.Length;
            ofn.lpstrFileTitle = new string(new char[64]);
            ofn.nMaxFileTitle = ofn.lpstrFileTitle.Length;
            ofn.lpstrTitle = dialogTitle;
            if (GetOpenFileName(ref ofn))
                return ofn.lpstrFile;
            return string.Empty;
        }
    }
}

Then, you can call it like so:

string filename = FilePicker.ShowDialog("C:\\", new string[] { "png", "jpeg", "jpg" }, "Image Files", "Select an Image File...");

Or, if you must use naitive, you can work around this bug by running the rest of your code as admin, and this not as admin using impersonation.

@AdamBraden
Copy link

@manodasanW - crashes right at the PickSingleFileAsync() call.

@derekhe
Copy link

derekhe commented Aug 11, 2022

Yes, the problem still exist in WinUI3 with admin right. Please fix this!

@AdamBraden
Copy link

After discussing this with the filesystem team, the recommendation is to use the IFileOpenDialog apis from CSWin32. Here is a recent thread discussing this very topic - FileOpenDialog in CsWin32.

@bogdan-patraucean
Copy link
Author

@AdamBraden thank you for oferring this workaround. Any updates related to fixing the issue?

@AdamBraden
Copy link

What we could consider is creating a WinAppSDK wrapper around IFileDialog apis that provide an equivalent to the Picker apis. There are some opportunities to improve as well - StorageFiles are very heavyweight objects, and so we could consider returning something more optimized.

Blinue added a commit to Blinue/Magpie that referenced this issue Oct 19, 2022
FileOpenPicker/FileSavePicker 不支持管理员身份,见 microsoft/WindowsAppSDK#2504
改为使用 IFileDialog
@bogdan-patraucean
Copy link
Author

@manodasanW, @MikeHillberg, @AdamBraden, hi! Any progress on this? I would appreciate an update. I'm curious how it goes.

@derekhe
Copy link

derekhe commented Dec 8, 2022

WinUI3 makes me crazy for even basic stuff is not working. I return back to use electron.

@bogdan-patraucean
Copy link
Author

bogdan-patraucean commented Dec 13, 2022

Indeed, such a simple thing like a FilePicker requires advanced knowledge and years of experience to understand. I'm a C# developer and I need to use unmanaged code with C++ to open a file picker...this is not how developement experience for WASDK should be.

@bogdan-patraucean
Copy link
Author

I just discovered that on Windows 10 it works. The problem is only on Windows 11.

@fredemmott
Copy link

Same problem on windows 10 here.

@bogdan-patraucean
Copy link
Author

Same problem on windows 10 here.

what version do you have?

@DarranRowe
Copy link

@tbrummel

#include <Windows.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Media.Devices.h>

#include <string>
#include <iostream>

int wmain()
{
	using namespace std;
	using namespace winrt::Windows::Media::Devices;

	wcout << wstring_view(MediaDevice::GetAudioRenderSelector()) << L"\n";
	return 0;
}

Screenshot 2023-09-24 195326

I just call it and it works.

@tbrummel
Copy link

tbrummel commented Sep 25, 2023

@DarranRowe

I wasn't trying to imply that that API never works. Your example has left out all of the "UI" in WinUI3. I have repros that work and repros that don't. I've got one now that fails 1 in every 4 or 5 runs on one PC (never from VS) and fails 100% on another PC. So, it looks like a threading/timing issue -- I'm guessing linked to the inner workings of the UI components of WinUI (as this is being executed by a WinUI control). I'll post back if I get it narrowed down. I do know that the crash is always on that API call (if it crashes).

I'm digging in to see if I can narrow down the root cause... but that is the point I was trying to make: I'm wasting a lot of time with the WinUI3 iteration of the MS UI Framework trying to get simple things working. I remember similar investigations with Avalon (WPF pre-release) so I'm not saying that WinUI won't get there eventually... but even without "issues", the code restrictions/sandboxing might just be too much for many desktop apps.

I'm currently developing the app simultaneously in WInUI3, WPF w/ WinRT libs (media), and WPF native - so I can compare the experiences.

@tbrummel
Copy link

@DarranRowe

Ok, so I started a new WinUI3 unpackaged app with the latest runtimes and then slowly added code/xaml to it until I could get it to crash. Here it is: If I bind an Image to a Button in the XAML and do the call to MediaDevice.GetAudioRenderSelector() from the loaded event of that control, I'll get the app to crash about 20% of the time. If I remove either the image(s) or the call to GetAudioRenderSelector, I cannot get it to crash.

So, there is a timing/threading issue with either binding in general or possibly the async loading of images and other APIs. I'm not convinced that this specific API call is key -- could be that anything I call at the "point" in the code might surface the issue -- but if I remove that call, I can't crash (and I don't have any other API calls in mind to try and really don't know if I want to invest any more time in this -- I'm moving back to WPF for now).

@bogdan-patraucean
Copy link
Author

bogdan-patraucean commented Oct 13, 2023

@AdamBraden, hello, some updates on this issue would be very appreciated.

@GID0317
Copy link

GID0317 commented Dec 17, 2023

December 17, No any update yet? This issue seems like almost a year but i cant see any update in this problem.

@PavlikBender
Copy link

Any news? I have same problem

@PavlikBender
Copy link

Thanks to @castorix . I found workaround for me and made interpretation of it https://github.com/PavlikBender/Pickers

@Balkoth
Copy link

Balkoth commented Apr 10, 2024

It's 2024 and Windows App SDK has no working file dialog. What an achievement.

@tbrummel
Copy link

Ah, seeing that new post reminded me that I never did follow up here.

I rewrote my music server app in WPF and it runs perfectly on Win 10 & 11 and I can deploy it (copy the files to another PC) with ease! I can also run it 24 hours a day -- and use memory! It's amazing! I think this WPF thing could catch on!

Or maybe I'm one of the few remaining developers who still write code they want to run on PCs and have no desire for a "UI framework" that throttles their memory usage and app performance. If I were targeting a mobile device or needed to worry about batteries, I would welcome such features -- and I'd probably have little need for an open file dialog.

This could be a simple case of misinformation - I was under the impression that WinUI3 was for writing desktop apps. Honestly, I wish it were, but I don't think a framework that arrests so much control from the developer is going to succeed for serious desktop apps.

@uixiu
Copy link

uixiu commented Apr 11, 2024

It's 2024 and Windows App SDK has no working file dialog. What an achievement.

Also, the browse folder picker can't pick the same folder next. To enable the selection button, one should trick the dialog buggy logic by going elsewhere and returning 😁. I went back to Winforms (win32) dialogs in WinUI 3.0 ✌🏻

@hclazarin
Copy link

hclazarin commented Jul 7, 2024

This was reported over 2 years ago, I can't believe there is still no acceptable solution or at least a reliable workaround. After 6 weeks working on a new major project facing issue after issue after issue with this SDK this is the last one, I give up. This framework is certainly a massive load of crap and will spank the architect who decided for it lol. I rather rollback to WPF and lose a few weeks than getting frustrated with nonsense every 3 days for the next few months.

@smourier
Copy link

smourier commented Aug 8, 2024

This was reported over 2 years ago, I can't believe there is still no acceptable solution or at least a reliable workaround.

FWIW, you can use Winforms's OpenFileDialog (or WPF) easily from WinUI3 https://stackoverflow.com/a/78842081/403671

@mominshaikhdevs
Copy link

mominshaikhdevs commented Aug 8, 2024

What we could consider is creating a WinAppSDK wrapper around IFileDialog apis that provide an equivalent to the Picker apis. There are some opportunities to improve as well - StorageFiles are very heavyweight objects, and so we could consider returning something more optimized.

YES. This is The Right Solution that should have been provided by Windows App SDK already.

#8 (comment)


@AdamBraden @manodasanW @MikeHillberg
It's really 2024. whats the latest update on this?

@Apollo199999999
Copy link

It's been 2 years and there's still no proper solution to this? Using WinForms OpenFileDialog as a workaround shouldn't be an acceptable solution.

@AlexanderBlackman
Copy link

This implementation works for me, but it's not on NuGet so you have to include it manually.
https://github.com/PavlikBender/Pickers

It's been 2 years and there's still no proper solution to this? Using WinForms OpenFileDialog as a workaround shouldn't be an acceptable solution.

I feel your pain, I checked this thread again today when the WinUI 3 Gallery proudly announced it added a FilePicker sample, but no, it is still as broken as usual.

@MartyIX
Copy link

MartyIX commented Sep 26, 2024

Hit this today in .NET MAUI with unpackaged mode. Frustrating bug. :|

@sungaila
Copy link

sungaila commented Sep 27, 2024

The picker situation is aweful right now. For a packaged Desktop app there are two options:

  • Win32 pickers: do not work in AppContainer/PartialTrust (no RuntimeBroker) and might not work in AOT (COM is not available in .NET compiled ahead of time)
  • WinRT pickers: do not work when elevated/with admin rights (COMException with no context) and do not work in AppContainer/PartialTrust (WinUI 3 has no CoreWindow)

So the only option might be to build a custom picker that uses WinRT APIs, I guess? What a mess.

@Cacsjep
Copy link

Cacsjep commented Oct 17, 2024

when you think for an whole hour you are crazy and you doing something wrong and founding then such a huge github issue about a file dialog, what the hell

@tbrummel
Copy link

Over 2 years and still no fix? This means that the project is ranked low in the dev team meetings and just never makes the cut for release. This means that the framework is targeting mobile apps (that could maybe also run on a desktop). I wish Microsoft would just make that clear. There are a lot of decisions to make in choosing platforms and APIs for a project and letting people know that WinUI is not being developed as a desktop focused solution (but it might work for some scenarios) would be nice. It's sad that developers are wasting time with debugging and investigation of issues that have been known for years -- and for what are clearly basic operations. I mean if you're trying to inject a custom shader into the UI pipeline, you might expect to run into some issues -- but not when trying to open a file!

I haven't revisited WinUI since my original post here and it has been on my "todo" list -- but I guess I can just remove it as there is, apparently, little progress in the direction I need for desktop/business apps/utilities. This truly saddens me. If/when I need to write a mobile photo viewer, I might check it out again...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-File access bug Something isn't working
Projects
None yet
Development

No branches or pull requests