KeiStory

728x90
반응형

.NET MAUI File Picker 사용하기

 

FilePicker 를 이용하여 파일은 선택하여 사용하는 방법입니다.

아래 예시는 이미지를 선택하는 방법입니다.

먼저 AndroidManifest.xml 에 파일로 사용될 파일 타입에 대한 권한을 추가합니다.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<!-- Required only if your app needs to access images or photos that other apps created -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<!-- Required only if your app needs to access videos that other apps created -->
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<!-- Required only if your app needs to access audio files that other apps created -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />

 

특정 버튼이 클릭되는 경우 png 이미지를 선택하여 처리하는 예시입니다.

private async void OnButtonClicked(object sender, EventArgs e)
{
    // 이미지 파일만
    PickOptions option = new PickOptions();
    option.PickerTitle = "Select Image File";
    option.FileTypes = FilePickerFileType.Images;

    var fileResult = await PickAndShow(option);

    if (fileResult != null)
    {
        var stream = await fileResult.OpenReadAsync();
        ImageSource source = ImageSource.FromStream(() => { return stream; });
    }
}

public async Task<FileResult?> PickAndShow(PickOptions options)
{
    try
    {
        var result = await FilePicker.Default.PickAsync(options);
        if (result != null)
        {
            if (result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase)
                || result.FileName.EndsWith("jpb", StringComparison.OrdinalIgnoreCase))
            {
                using var stream = await result.OpenReadAsync();
                var image = ImageSource.FromStream(() => stream);
            }
        }

        return result;
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }

    return null;
}

 

참고

https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/file-picker?view=net-maui-8.0&tabs=android

 

File picker - .NET MAUI

Learn how to use the .NET MAUI IFilePicker interface in the Microsoft.Maui.Storage namespace, which lets a user choose one or more files from the device.

learn.microsoft.com

 

728x90
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band