안녕하세요. 이동규(LiveDK) 입니다.

이번 내용에서는 Windows Phone에서 Application의 저장공간에 대해 알아보려고 합니다. Windows Phone 7에 설치되는 모든 프로그램은 내부 메모리에 각자만의 저장공간을 가지게 됩니다. 또한 모든 I/O(입출력)는 Isolated Storage에서 제한됩니다. 이 말은 어플리케이션상에서 다른 어플리케이션 Isolated storage에 접근 할 수 없다는 것입니다. 이러한 강력한 제한은 보안과 유효하지 않는 접근을 막을 수 있습니다.

Isolated Storage API는 아래의 namespace 를 사용하여 접근 할 수 있습니다.

using System.IO.IsolatedStorage;

이제 Isolated Storage의 Class 와 목적 들을 살펴 보겠습니다.

System.IO.IsolatedStorage.IsolatedStorageException
System.IO.IsolatedStorage.IsolatedStorageFile
System.IO.IsolatedStorage.IsolatedStorageSettings
System.IO.IsolatedStorage.IsolatedFileStream
  1. IsolatedStorageException - Isolated Storage 에서 작업이 실패하였을 경우 Exception 발생을 처리합니다.
  2. IsolatedStorageFile - Isolated Storage 구역안에서 파일 및 폴더를 관리합니다.
  3. IsolatedStorageSettings - Application 에서 Setting 값(key-value의 쌍으로)들을 저장할 수 있습니다. Dictionary<(Of <(TKey, TValue>)>)
  4. IsolatedFileStream - Isolated Storage 내에 저장된 파일에 대한 File Stream을 노출합니다.

지금까지 간단하게 Isolated Storage의 Class 그리고 내부적으로 어디까지 access 가능한지를 살펴 보았습니다. 지금부터는 코드를 들여다 보면서 실전 사용법을 익혀 보겠습니다. 이번 작업들을 통해 습득하게 될 내용은 다음과 같습니다.

1. Isolated Storage에 Data 폴더/파일생성 및 쓰기(Write)
2. Isolated Storage에 Data 읽기(Read)

이전 자료(Windows Phone - #2 A First Silverlight Phone Program)에서 개발환경 셋팅과 첫 번째 Silverlight for Windows Phone 를 만들어 보았기 때문에 처음부터 차근차근 설명은 하지 않겠습니다. Visual Studio를 실행 하여 File|New Proejct 를 차례대로 눌러 Silverlight for Windows Phone 에서 Windows Phone Application을 선택하여 적당한 프로젝트 이름정하고 OK를 눌러 프로젝트를 하나 생성합니다.

그림2. UI 디자인


그림1. 과 같이 UI를 디자인합니다. TextBox의 내용을 Write to Storage 버튼이벤트를 통해 Isolated Storage에 저장하고, Read from Storage 버튼이벤트를 통해 TextBlock에 저장된 내용을 보여주는 구성입니다.

Design View 상에서 올려 놓은 두개의 버튼을 두번 클릭하거나 Properties 에서 Click 이벤트를 지정해주거나 코드비하인드에서 이벤트 핸들러를 작성하여 이벤트를 작성합니다. 아래와 같이 두개의 이벤트를 처리할 수 있는 코드가 생성된것을 확인 할 수 있습니다.

namespace IsolatedStorageTest

{

    public partial class MainPage : PhoneApplicationPage

    {

        // Constructor

        public MainPage()

        {

            InitializeComponent();

        }

 

        //Button Event - Write to Stotage

        private void buttonWrite_Click(object sender, RoutedEventArgs e)

        {

        }

 

        //Button Event - Read from Stotage

        private void buttonRead_Click(object sender, RoutedEventArgs e)

        {

        }

    }

}


buttonWrite_Click 에서는 TextBox 에 저장된 내용을 Isolated Storage에 하나의 파일로 저장해야 하므로 다음 아래와 같은 코드를 작성해 줍니다.

//IsolatedStorage 저장소를 가져 옵니다.

IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();

 

//Folder 하나 생성합니다.

isoFile.CreateDirectory("Setting");

 

//FileMode Open Or Create 이고, 경로가 아래와 같은 IsolatedStorageFileStream.

IsolatedStorageFileStream isoFileStream = new IsolatedStorageFileStream(@"Setting\test.txt", FileMode.OpenOrCreate, isoFile);

StreamWriter writeFile = new StreamWriter(isoFileStream);

writeFile.WriteLine(textBoxWrite.Text); //TextBox 내용을 작성합니다.

writeFile.Close();  //Stream Close

buttonRead_Click 에서는 Isolated Storage에 저장된 내용을 TextBlock에 뿌려주는 작업입니다. 아래와 같이 작성하며 이번에도 코드 주석으로 설명하겠습니다.

//IsolatedStorage 저장소를 가져옵니다.

IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();

StreamReader sReader = null;

try

{

    //FileMode Open 이고, 경로가 아래와 같은 IsolatedStorageFileStream.

    sReader = new StreamReader(new IsolatedStorageFileStream(@"Setting\test.txt", FileMode.Open, isoFile));

    textBlockRead.Text = sReader.ReadLine();// 라인을 읽어들여 TextBlock 저장한다

    sReader.Close();

}

catch   //파일읽기 실패시 오류처리 - Write 한번도 이루어 지지 않아 파일이 없는경우

{

    textBlockRead.Text = "파일이 존재 하지 않습니다.";

}

에뮬레이터에서 실제 동작하는 모습을 캡쳐해 보았습니다.
순서는 Read - (에러확인) - 글쓰기 - Write - Read - (정상확인) - 뒤로가기 - 실행 - Read - (정상확인)
여기서 특별히 확인해 볼 사항은 뒤로가기후 실행에서 저장된 파일을 제대로 불러오는 것입니다.

 

참고자료
Programming Windows Phone 7 by Charles Petzold
Isolated Storage Overview http://msdn.microsoft.com/ko-kr/library/ff402541(en-us,VS.92).aspx
Isolated Storage Sample http://msdn.microsoft.com/ko-kr/library/ff626519(v=VS.92).aspx
Posted by Dongkyu
,