방법: 애플리케이션 세션 간의 애플리케이션 범위 속성 유지 및 복원
이 예제는 애플리케이션이 종료될 때 애플리케이션 범위 속성을 유지하는 방법과 애플리케이션이 다음에 시작될 때 애플리케이션 범위 속성을 복원하는 방법을 보여 줍니다.
예제
애플리케이션은 애플리케이션 범위 속성을 격리된 스토리지에 유지 및 복원합니다. 격리된 스토리지는 파일 액세스 권한 없이 애플리케이션이 안전하게 사용할 수 있는 보호된 스토리지 영역입니다. App.xaml 파일은 다음 XAML의 강조 표시된 줄에 나온 것처럼 App_Startup
메서드를 Application.Startup 이벤트의 처리기로, App_Exit
메서드를 Application.Exit 이벤트의 처리기로 정의합니다.
참고 항목
다음 XAML은 CSharp용으로 작성되었습니다. Visual Basic 버전은 클래스 선언을 생략합니다.
<Application x:Class="SDKSamples.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
Startup="App_Startup"
Exit="App_Exit">
</Application>
다음 예제에서는 XAML에 대한 이벤트 처리기를 포함하는 애플리케이션 코드 숨김을 보여 줍니다. App_Startup
메서드는 애플리케이션 범위 속성을 복원하고 App_Exit
메서드는 애플리케이션 범위 속성을 저장합니다.
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows;
namespace SDKSamples
{
public partial class App : Application
{
string _filename = "App.data";
public App()
{
// Initialize application-scope property
Properties["NumberOfAppSessions"] = "0";
}
private void App_Startup(object sender, StartupEventArgs e)
{
// Restore application-scope property from isolated storage
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForDomain();
try
{
if (storage.FileExists(_filename))
{
using (IsolatedStorageFileStream stream = storage.OpenFile(_filename, FileMode.Open, FileAccess.Read))
using (StreamReader reader = new StreamReader(stream))
{
// Restore each application-scope property individually
while (!reader.EndOfStream)
{
string[] keyValue = reader.ReadLine().Split(new char[] { ',' });
Properties[keyValue[0]] = keyValue[1];
}
}
}
}
catch (DirectoryNotFoundException ex)
{
// Path the file didn't exist
}
catch (IsolatedStorageException ex)
{
// Storage was removed or doesn't exist
// -or-
// If using .NET 6+ the inner exception contains the real cause
}
}
private void App_Exit(object sender, ExitEventArgs e)
{
// Increase the amount of times the app was opened
Properties["NumberOfAppSessions"] = int.Parse((string)Properties["NumberOfAppSessions"]) + 1;
// Persist application-scope property to isolated storage
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForDomain();
using (IsolatedStorageFileStream stream = storage.OpenFile(_filename, FileMode.Create, FileAccess.Write))
using (StreamWriter writer = new StreamWriter(stream))
{
// Persist each application-scope property individually
foreach (string key in Properties.Keys)
writer.WriteLine("{0},{1}", key, Properties[key]);
}
}
}
}
Imports System.IO
Imports System.IO.IsolatedStorage
Class Application
Private _filename As String = "App.data"
Public Sub New()
' Initialize application-scope property
Properties("NumberOfAppSessions") = "0"
End Sub
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
' Restore application-scope property from isolated storage
Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForDomain()
Try
If storage.FileExists(_filename) Then
Using stream As IsolatedStorageFileStream = storage.OpenFile(_filename, FileMode.Open, FileAccess.Read)
Using reader As New StreamReader(stream)
' Restore each application-scope property individually
Do While Not reader.EndOfStream
Dim keyValue() As String = reader.ReadLine().Split(New Char() {","c})
Properties(keyValue(0)) = keyValue(1)
Loop
End Using
End Using
End If
Catch ex As DirectoryNotFoundException
' Path the file didn't exist
Catch ex As IsolatedStorageException
' Storage was removed or doesn't exist
' -or-
' If using .NET 6+ the inner exception contains the real cause
End Try
End Sub
Private Sub App_Exit(ByVal sender As Object, ByVal e As ExitEventArgs)
'Increase the amount of times the app was opened
Properties("NumberOfAppSessions") = Integer.Parse(DirectCast(Properties("NumberOfAppSessions"), String)) + 1
' Persist application-scope property to isolated storage
Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForDomain()
Using stream As IsolatedStorageFileStream = storage.OpenFile(_filename, FileMode.Create, FileAccess.Write)
Using writer As New StreamWriter(stream)
' Persist each application-scope property individually
For Each key As String In Properties.Keys
writer.WriteLine("{0},{1}", key, Properties(key))
Next key
End Using
End Using
End Sub
End Class
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET Desktop feedback