어플리케이션/WinUi(C#)

WinUi 3 파일 저장(FileSavePicker)

인공지능싱글톤 2023. 12. 4. 19:37

MS 참고 사이트

 

FileSavePicker Class (Windows.Storage.Pickers) - Windows UWP applications

Represents a file picker that lets the user choose the file name, extension, and storage location for a file. In a desktop app, before using an instance of this class in a way that displays UI, you'll need to associate the object with its owner's window ha

learn.microsoft.com

 

App.xaml.cs 파일

private Window m_window; => public static Window m_window { get; private set; } 변경

public partial class App : Application
{
	/// <summary>
	/// Initializes the singleton application object.  This is the first line of authored code
	/// executed, and as such is the logical equivalent of main() or WinMain().
	/// </summary>
	public App()
	{
		this.InitializeComponent();
	}

	/// <summary>
	/// Invoked when the application is launched.
	/// </summary>
	/// <param name="args">Details about the launch request and process.</param>
	protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
	{
		m_window = new MainWindow();
		m_window.Activate();
	}

	public static Window m_window { get; private set; }
}

 

MainWindow.xaml.cs 파일

private async void myButton_Click(object sender, RoutedEventArgs e)
{
	var savePicker = new Windows.Storage.Pickers.FileSavePicker();
	savePicker.SuggestedStartLocation = PickerLocationId.Desktop;

	// 확장자 설정
	savePicker.FileTypeChoices.Add(".txt확장자", new List<string>() { ".txt" });
	savePicker.FileTypeChoices.Add(".csv확장자", new List<string>() { ".csv" });

	// 기복 파일 이름 설정
	savePicker.SuggestedFileName = "파일이름";

	nint windowHandle = WindowNative.GetWindowHandle(App.m_window);

	InitializeWithWindow.Initialize(savePicker, windowHandle);
	Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
	if (file != null)
	{
		Windows.Storage.CachedFileManager.DeferUpdates(file);

		// 파일 내용 작성(방식 1)
		await Windows.Storage.FileIO.WriteTextAsync(file, "내용");

		//// 파일 내용 작성(방식 2)
		//List<string> txtList = new List<string>();
		//string txt = "안녕";
		//txtList.Add(txt);
		//await Windows.Storage.FileIO.WriteLinesAsync(file, txtList);

		Windows.Storage.Provider.FileUpdateStatus status =
			await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
		if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
		{
			// 카드 저장 성공 이벤트
		}
		else
		{
			// 카드 저장 실패 이벤트
		}
	}
	else
	{
		// 파일 저장 취소 이벤트
	}
}

 

결과