Local app data จัดเก็บไฟล์ลง Storage บน Windows Store Apps (C#)       | 
   
 
			  
			  
                Local app data จัดเก็บไฟล์ลง Storage บน Windows Store Apps (C#) ในการเขียน Apps บน Windows Store  สิ่งที่สำคัญอย่างหนึ่ง คือการจัดเก็บข้อมูล โดยข้อมูลที่จะจัดเก็บบน Apps นั้น สามารถแบ่งได้เป็น 2-3 ประเภท คือ ค่าตัวแปรหรือ Settings หรือข้อมูลประเภทไฟล์ต่าง ๆ ที่เกิดจากการใช้งาน Apps หรือไฟล์ที่ต้องการทำมาใช้กับ Apps เช่นรูปภาพ , ไฟล์มีเดีย , เท็กไฟล์ เป็นต้น 
 
และการจัดเก็บข้อมูลบน Windows Store Apps นั้นจะถูกแบ่งออกเป็น 3 ประเภทใหญ่ ๆ คือ Local app data , Roaming app data  และ Temporary app data โดยแต่ล่ะประเภทจะมีวัตถุประสงค์ที่แตกต่างกันไป โดยในหัวข้อนี้จะพูดถึง Local app data ซึ่งจะเป็นการจัดเก็บข้อมูลลงใน Apps โดยตรง และสามารถใช้ได้เฉพาะเครื่องนั้น ๆ เท่านั้น รูปแบบการจัดเก็บ เก็บได้ทั้งค่าตัวแปร Setting หรือจะเป็นไฟล์ต่าง ๆ ได้ทุกประเภท 
 
ตัวอย่างการจัดเก็บค่าแบบ Settings 
 
สร้างตัวแปร Settings 
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["exampleSetting"] = "Hello Windows";
  
อ่านตัวแปร Settings 
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Object value = localSettings.Values["exampleSetting"];
  
 
 
 
ตัวอย่างการจัดเก็บค่าแบบ Object 
 
สร้างตัวแปร Object 
Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();
composite["intVal"] = 1;
composite["strVal"] = "string";
localSettings.Values["exampleCompositeSetting"] = composite;
  
อ่านตัวแปร Object 
Windows.Storage.ApplicationDataCompositeValue composite = 
   (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["exampleCompositeSetting"];
if (composite == null)
{
   // No data
}
else
{
   // Access data in composite["intVal"] and composite["strVal"]
}
 
 
ตัวอย่างการจัดเก็บแบบ Text file 
 
การจัดเก็บแบบ Text file 
async void WriteTimestamp()
{
   Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = 
       new Windows.Globalization.DatetimeFormatting.DateTimeFormatter("longtime");
   StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", 
       CreateCollisionOption.ReplaceExisting);
   await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
}
 
การอ่าน Text file 
async void ReadTimestamp()
{
   try
   {
      StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
      String timestamp = await FileIO.ReadTextAsync(sampleFile);
      // Data is contained in timestamp
   }
   catch (Exception)
   {
      // Timestamp not found
   }
}
 
 
ลองมาดูตัวอย่างเพื่อความเข้าใจมากขึ้น 
 
  
 
สร้าง Page ขึ้นมา 2 Page โดยเพจแรกใช้สร้างตัวแปร และ เพจสอง ใช้สำหรับการอ่านค่า 
 
  
 
เพจแรกใช้สร้างค่า 
 
  
 
เพจสองใช้สำหรับการแสดงค่า 
 
Example 1 สร้างตัวแปร Settings และอ่านตัวแปร Settings (Local app data) 
 
MainPage.xaml 
<Page
    x:Class="WindowsStoreApps.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblStatus" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Status"/>
        <Button x:Name="btnGoPage2" Content="Go to Page 2" HorizontalAlignment="Left" Margin="90,135,0,0" VerticalAlignment="Top" Height="59" Width="113" Click="btnGoPage2_Click"/>
    </Grid>
</Page>
 
MainPage.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            localSettings.Values["exampleSetting"] = "Hello Windows";
            this.lblStatus.Text = "Local data has been created.";
        }
        private void btnGoPage2_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Page2));
        }
       
    }
}
 
Page2.xaml 
<Page
    x:Class="WindowsStoreApps.Page2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblResult" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Result"/>
    </Grid>
</Page>
 
Page2.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Page2 : Page
    {
        public Page2()
        {
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Object value = localSettings.Values["exampleSetting"];
            this.lblResult.Text = value.ToString();
        }
    }
}
 
Screenshot 
 
  
 
สร้างค่าตัวแปร 
 
  
 
แสดงค่าตัวแปร 
 
 
Example 2 สร้างตัวแปร Object และอ่านตัวแปร Object  (Local app data) 
 
MainPage.xaml 
<Page
    x:Class="WindowsStoreApps.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblStatus" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Status"/>
        <Button x:Name="btnGoPage2" Content="Go to Page 2" HorizontalAlignment="Left" Margin="90,135,0,0" VerticalAlignment="Top" Height="59" Width="125" Click="btnGoPage2_Click"/>
    </Grid>
</Page>
 
MainPage.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();
            composite["intVal"] = 1;
            composite["strVal"] = "My Value";
            localSettings.Values["exampleCompositeSetting"] = composite;
            this.lblStatus.Text = "Local data has been created.";
        }
        private void btnGoPage2_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Page2));
        }
    }
}
 
 
 
 
Page2.xaml 
<Page
    x:Class="WindowsStoreApps.Page2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblResult" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Result"/>
    </Grid>
</Page>
 
Page2.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Page2 : Page
    {
        public Page2()
        {
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Windows.Storage.ApplicationDataCompositeValue composite = (Windows.Storage.ApplicationDataCompositeValue) localSettings.Values["exampleCompositeSetting"];
            if (composite != null)
            {
                this.lblResult.Text = "intVal = " + composite["intVal"] + " and strVal = " + composite["strVal"];
            }
        }
    }
}
 
Screenshot 
 
  
 
สร้างตัวแปร 
 
  
 
แสดงค่าตัวแปร 
 
 
Example 3 สร้าง Text file และการอ่าน Text file (Local app data) 
 
MainPage.xaml 
<Page
    x:Class="WindowsStoreApps.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblStatus" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Status"/>
        <Button x:Name="btnGoPage2" Content="Go to Page 2" HorizontalAlignment="Left" Margin="90,135,0,0" VerticalAlignment="Top" Height="59" Width="125" Click="btnGoPage2_Click"/>
    </Grid>
</Page>
 
MainPage.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            string myString = "Welcome to ThaiCreate.Com";
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt",
                Windows.Storage.CreationCollisionOption.ReplaceExisting);
            await Windows.Storage.FileIO.WriteTextAsync(sampleFile, myString);
            this.lblStatus.Text = "Text file has been created.";
        }
        private void btnGoPage2_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Page2));
        }
       
    }
}
 
Page2.xaml 
<Page
    x:Class="WindowsStoreApps.Page2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="lblResult" HorizontalAlignment="Left" Margin="93,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="30" Text="Result"/>
    </Grid>
</Page>
 
Page2.xaml.cs 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Page2 : Page
    {
        public Page2()
        {
            this.InitializeComponent();
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            try
            {
                Windows.Storage.StorageFile sampleFile = await localFolder.GetFileAsync("dataFile.txt");
                String myString = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
                this.lblResult.Text = myString;
            }
            catch (Exception)
            {
                // Exception Error
            }
        }
    }
}
 
Screenshot 
 
  
 
สร้าง Text file 
 
  
 
แสดงค่าใน Text file 
 
อ่านเพิ่มเติม 
 
 
 
.              
  
              			
			  
								  
			  
  
                          
  | 
           
          
            
			  ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท 
              | 
           
          
 
       
		 
					
        
          
            
                
                   | 
                 
                
                  |   | 
                  By :  | 
                  ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)  | 
                 
                
                  |   | 
                  Score Rating :  | 
                  
				   				   | 
                    | 
                 
                
                  |   | 
                  Create/Update Date :  | 
                  
                    2014-03-17 12:17:04            /
            2017-03-19 14:55:51 | 
                 
				
				
				                
                  |   | 
                  Download :  | 
                   
				 No files				   | 
                 
				              | 
           
         
		
      
         
           
            
            
              
                | 
               
                   Sponsored Links / Related |  
              | 
         
        
                        | 
          
		  
		   | 
         
         
          |             
		  
	
      
     | 
     
 
 
		  
         | 
		
          
		   
		  
              
      
     |