티스토리 뷰

반응형

Windows 8 store app에서 여러가지 작업을 하다가 접하는 문제 중에 하나가 파일을 읽어 들여서 사용해야 하는 경우에 Encodig문제가 발생한다. 그래서 간단하게 셈플을 만들었다.

(방법을 알면 정말 쉽게 할 수 있는데..모르면 정말..)

 

How to read a text file with other encoding than UFT8 or UTF16 in WinRT?

http://stackoverflow.com/questions/12935238/how-to-read-a-text-file-with-other-encoding-than-uft8-or-utf16-in-winrt

 

1. 화면

 

 

 

2. ItemDetailPage.xaml.cs

//ToArray()를 사용하기 위해 필요
using System.Runtime.InteropServices.WindowsRuntime;

    public sealed partial class ItemDetailPage : FileReadSample.Common.LayoutAwarePage
    {
        public ItemDetailPage()
        {
            this.InitializeComponent();

            //스크롤 뷰어 뷰 체인지 이벤트를 이용해서 위치 표시
            scrollViewer.ViewChanged +=
                (s, e) =>
                {
                    scrollPos.Text = scrollViewer.HorizontalOffset.ToString();
                };
        }

        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// 택스트 파일 열기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //파일 피커
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            openPicker.FileTypeFilter.Add(".txt");
            //파일 하나 선택
            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                //파일이 존재하면
                //내용을 버퍼에 읽어 들이고
                var buffer = await FileIO.ReadBufferAsync(file);
                //배열로 바꾸고
                var fileData = buffer.ToArray();
                //euc-Kr로 인코딩
                var encoding = Encoding.GetEncoding("euc-Kr");
                //파일명 출력
                title.Text = file.Name;
                //파일 패스 출력
                subtitle.Text = file.Path;
                //내용 출력
                var contents = encoding.GetString(fileData, 0, fileData.Length);
                textContent.Text = contents;
            }
        }
    }

 

3. ItemDetailPage.xaml

...

        <UserControl Margin="0,0,0,0" Grid.RowSpan="2">
            <ScrollViewer x:Name="scrollViewer" Style="{StaticResource HorizontalScrollViewerStyle}" Grid.Row="1">
                <common:RichTextColumns x:Name="richTextColumns" Margin="117,120,117,47">

                    <common:RichTextColumns.ColumnTemplate>
                        <DataTemplate>
                            <RichTextBlockOverflow Margin="80,0,0,0" Width="560">
                                <RichTextBlockOverflow.RenderTransform>
                                    <TranslateTransform X="-1" Y="4"/>
                                </RichTextBlockOverflow.RenderTransform>
                            </RichTextBlockOverflow>
                        </DataTemplate>
                    </common:RichTextColumns.ColumnTemplate>
                   
                    <RichTextBlock x:Name="richTextBlock" IsTextSelectionEnabled="False" Style="{StaticResource ItemRichTextStyle}" Width="560">
                        <Paragraph>
                            <Run x:Name="title" FontWeight="Light" FontSize="26.667" />
                            <LineBreak/>
                            <LineBreak/>
                            <Run x:Name="subtitle" FontWeight="Normal" FontSize="20" />
                            <LineBreak/>
                        </Paragraph>
                        <Paragraph>
                            <Run x:Name="textContent" FontWeight="SemiLight" FontSize="18" />
                        </Paragraph>
                    </RichTextBlock>

                </common:RichTextColumns>

            </ScrollViewer>
        </UserControl>

...

 

4. Source

 

FileReadSample.zip

반응형

'Previous Platforms > Samples' 카테고리의 다른 글

Using Task, Async, Await  (0) 2013.07.28
Custom Behavior Sample  (0) 2012.12.25
WinRT File Based Database sample  (0) 2012.11.12
Tile + BackgroundTask = LiveTile APP!  (0) 2012.10.30
InputPane using Popup sample  (0) 2012.10.29
댓글