Thứ Sáu, 3 tháng 9, 2010

C#: Đọc/ghi resource

Ví dụ về cách sử dụng ResourceWriterResourceSet

Class ResourceBuilder:

  public class ResourceBuilder

    {

        public static void Write(DataTable data, string fileName)

        {

            FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);

            ResourceWriter resourceWriter = new ResourceWriter(stream);

            foreach (DataRow row in data.Rows)

                resourceWriter.AddResource(row[0].ToString(), row[1]);

 

            resourceWriter.Generate();

            resourceWriter.Close();

        }

        public static DataTable Read(string fileName)

        {

            FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);

            ResourceSet Rs = new ResourceSet(stream);

            DataTable data = new DataTable();

 

            data.Columns.Add("Key");

            data.Columns.Add("Value");

 

          

            IDictionaryEnumerator resourceReaderEn = Rs.GetEnumerator();

            while (resourceReaderEn.MoveNext())

                data.Rows.Add(new object[] { resourceReaderEn.Key,resourceReaderEn.Value });

 

            Rs.Close();

            return data;

        }

 

        public static DataTable Read(string fileName, params string[] keys)

        {

            FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);

            ResourceSet Rs = new ResourceSet(stream);

            DataTable data = new DataTable();

 

            data.Columns.Add("Key");

            data.Columns.Add("Value");

 

            foreach (string key in keys)

                data.Rows.Add(new object[] { key, Rs.GetString(key) });

           

            Rs.Close();

            return data;

        }

    }

Sử dụng ResourceBuilder:

    static void Main(string[] args)

        {

            string fileName = @"D:\Vie.resources";

            DataTable data = new DataTable();

 

            data.Columns.Add("Key");

            data.Columns.Add("Value");

 

            data.Rows.Add(new object[] {"Yes", "Đồng ý" });

            data.Rows.Add(new object[] { "No", "Từ chối" });

            data.Rows.Add(new object[] { "Ok", "Đồng ý" });

            data.Rows.Add(new object[] { "Cancel", "Huỷ" });

 

            ResourceBuilder.Write(data, fileName);

            data = ResourceBuilder.Read(fileName, new string[] {"No", "Cancel1"});

            foreach(DataRow row in data.Rows)

                Debug.WriteLine(string.Format("{0} = {1}", row[0], row[1]));

}


Có thể sử dụng ResourceManager, tham khảo

http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx

Không có nhận xét nào:

Đăng nhận xét