StorageHelper 는 윈도우8 어플에서 xml 읽고 쓰기 적당한 클래스 입니다.
하지만 아쉽게 "windows 8 consumer" 버전에서 만든 소스이다. 윈도우8 RTM 버전에서도 잘 돌아 가지만, DataContractSerializer 등의 함수로 구현되지 않았습니다.
원래대로라면 DataContractSerializer 를 이용해서 serializer 해서 저장하여야 한다.
UserDetail Stats = new UserDetail();
Stats.Id = 1005;
Stats.Name = "name5";
StorageFile userdetailsfile = await roamingFolder.CreateFileAsync("UserDetails", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetail));
serializer.WriteObject(outStream.AsStreamForWrite(), Stats);
await outStream.FlushAsync();
}
아래의 소스부분 제가 일부 수정한것으로 사용하세요!
아래의 소스의 저장 부분을 수정해서 사용해라!~!!!
http://social.msdn.microsoft.com/Forums/is/winappswithcsharp/thread/3a2dddab-03fc-449a-a1e5-fbec6f40c10d
public async Task<T> SaveASync(T Obj, string FileName)
{
FileName = FileName + ".xml";
try
{
if (Obj != null)
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
{
serializer.Serialize(outStream, Obj);
}
}
}
return default(T);
}
catch (FileNotFoundException)
{
//file not existing is perfectly valid so simply return the default
return default(T);
}
catch (Exception)
{
throw;
}
}
ObjectStorageHelper<T> now available for Windows 8 RTM (Windows 8 Xml Utility) Source!
아래의 헬퍼 클래스를 참고하여 사용하면 됩니다. 사용법은 간단합니다.
1건을 저장하는 경우
Student objStudent = new Student { Name = "DJ ", RollNumber = 1 };
var objectStorageHelper = new QuickTodoListTable.Data.Util.StorageHelper.ObjectStorageHelper<Student>(QuickTodoListTable.Data.Util.StorageHelper.StorageType.Local);
objectStorageHelper.SaveASync(objStudent, "abc");
여러건을 저장하는 경우
List<doItem> lstStudent = new List<doItem>()
{new doItem { ID = Convert.ToDateTime("2012-10-12 14:55:16"), Subject = "주제1", Memo = "메모1", Group = 1, Sdate = Convert.ToDateTime("2012-10-12 14:11:12"), Edate = Convert.ToDateTime("2012-10-12 14:11:12"), Point = 1, StateMemo = 1},
new doItem { ID = Convert.ToDateTime("2012-10-13 14:55:26"), Subject = "주제2", Memo = "메모2", Group = 2, Sdate = Convert.ToDateTime("2022-10-22 14:22:22"), Edate = Convert.ToDateTime("2012-10-12 15:12:12"), Point = 2, StateMemo = 2},
new doItem { ID = Convert.ToDateTime("2012-10-14 14:55:36"), Subject = "주제3", Memo = "메모3", Group = 3, Sdate = Convert.ToDateTime("2012-10-12 14:11:12"), Edate = Convert.ToDateTime("2012-10-12 14:11:12"), Point = 3, StateMemo = 3}
};
var objectStorageHelper = new QuickTodoListTable.Data.Util.StorageHelper.ObjectStorageHelper<List<doItem>>(QuickTodoListTable.Data.Util.StorageHelper.StorageType.Local);
objectStorageHelper.SaveASync(lstStudent, "abc");
1건을 읽어오기
////new up ObjectStorageHelper specifying that we want to interact with the Local storage folder
var objectStorageHelper = new QuickTodoListTable.Data.Util.StorageHelper.ObjectStorageHelper<Student>(QuickTodoListTable.Data.Util.StorageHelper.StorageType.Local);
//Get the object from the storage folder
Student myPoco = await objectStorageHelper.LoadASync("abc");
여러건을 읽어오기
var objectStorageHelper = new QuickTodoListTable.Data.Util.StorageHelper.ObjectStorageHelper<List<doItem>>(QuickTodoListTable.Data.Util.StorageHelper.StorageType.Local);
List<doItem> lsdoLIst = await objectStorageHelper.LoadASync("abc");
doItem doItem1 = new doItem { ID = Convert.ToDateTime("2012-10-12 14:55:16"), Subject = "주제9", Memo = "메모9", Group = 9, Sdate = Convert.ToDateTime("2012-10-12 14:11:12"), Edate = Convert.ToDateTime("2012-10-12 14:11:12"), Point = 1, StateMemo = 1 };
lsdoLIst.Add(doItem1);
foreach (var r in lsdoLIst)
{
string n = r.Subject;
}
toDoList를 만들때 데이터를 저장 처리할때, xml을 사용합니다. 개발소스 일부였습니다. 읽고, 쓰고 할때 대량 또는 1건을 처리해야 할 경우 사용하면 유용합니다.
ObjectStorageHelper<T> now available for Windows 8 RTM (Windows 8 Xml Utility) Source!
Download
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;
using Windows.Storage.Streams;
namespace QuickTodoListTable.Data.Util
{
public class StorageHelper
{
public enum StorageType
{
Roaming, Local, Temporary
}
public class ObjectStorageHelper<T>
{
private ApplicationData appData = Windows.Storage.ApplicationData.Current;
public XmlSerializer serializer;
private StorageType storageType;
//http://support.microsoft.com/kb/330592/ko
public ObjectStorageHelper(XmlSerializer serializer)
{
this.serializer = serializer;
}
public ObjectStorageHelper(StorageType StorageType)
{
serializer = new XmlSerializer(typeof(T));
storageType = StorageType;
}
public async void DeleteASync(string FileName)
{
FileName = FileName + ".xml";
try
{
StorageFolder folder = GetFolder(storageType);
var file = await GetFileIfExistsAsync(folder, FileName);
if (file != null)
{
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
catch (Exception)
{
throw;
}
}
public async void SaveASync(T Obj, string FileName)
{
FileName = FileName + ".xml";
try
{
if (Obj != null)
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
serializer.Serialize(outStream, Obj);
}
}
catch (Exception)
{
throw;
}
}
public async Task<T> LoadASync(string FileName)
{
FileName = FileName + ".xml";
try
{
StorageFile file = null;
StorageFolder folder = GetFolder(storageType);
file = await folder.GetFileAsync(FileName);
IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
return (T)serializer.Deserialize(inStream);
}
catch (FileNotFoundException)
{
//file not existing is perfectly valid so simply return the default
return default(T);
//throw;
}
catch (Exception)
{
//Unable to load contents of file
throw;
}
}
private StorageFolder GetFolder(StorageType storageType)
{
StorageFolder folder;
switch (storageType)
{
case StorageType.Roaming:
folder = appData.RoamingFolder;
break;
case StorageType.Local:
folder = appData.LocalFolder;
break;
case StorageType.Temporary:
folder = appData.TemporaryFolder;
break;
default:
throw new Exception(String.Format("Unknown StorageType: {0}", storageType));
}
return folder;
}
private async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
{
try
{
return await folder.GetFileAsync(fileName);
}
catch
{
return null;
}
}
}
}
}
Introduction
Windows 8 Storage Helper, helps you create/read a Text(.txt) file.
Also it can save as image from a given web url.
Usage
To Create a Text File
To Read a Text File
To Save as Image from a URL
Follow me in twitter: http://twitter.com/dpatra
댓글 없음:
댓글 쓰기