将对象存储到Windows 8应用程序中的文件 [英] Storing an object to a file in Windows 8 apps

查看:91
本文介绍了将对象存储到Windows 8应用程序中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(Windows 8应用程序,C#)



我在每个对象中都有许多图像(.jpg)和音频文件(.mp3)。我想将这些对象存储在单独的文件中,然后再检索内容。我搜索了对象序列化,但找不到适合Windows 8应用程序的示例。

那么,在Windows 8应用程序(C#)中将对象保存到文件的方法是什么。

如果是对象序列化,请提供示例代码或一个链接。

解决方案

请看我对这个问题的评论。



最好的方法是也许是数据合同

http:// msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ]。



请参阅我过去的答案,我提倡这种方法:

< a href =http://www.codeproject.com/Answers/136502/How-can-I-utilize-XML-File-streamwriter-and-reader#answer1>我如何利用我的XML文件编写器和阅读器表单申请? [ ^ ],

创建属性文件...... [ ^ ],

deseralize json字符串数组 [ ^ ]。



答案与.NET有关,强烈推荐。如果你不使用任何.NET语言,请不要责怪我:你甚至没有提到你正在使用的语言。



对于C ++(不是C ++ / CLI),例如,我建议寻找boost序列化: http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html [ ^ ]。



- SA


Quote:

那么,将对象保存到文件的方法是什么在Windows 8应用程序(C#)中。



看看这个提示:

Windows 8 App - 使用Windows.Storage命名空间的文件中的数据存储 [ ^ ]


我收到异常:

System.Runtime.Serialization.dll中出现System.Runtime.Serialization.InvalidDataContractException类型的异常,但未在用户代码中处理



附加信息:类型''Windows.UI.Xaml.Media.ImageSource''无法序列化。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。如果类型是集合,请考虑使用CollectionDataContractAttribute对其进行标记。有关其他支持的类型,请参阅Microsoft .NET Framework文档。



在serializer.WriteObject(stream1,record1)



该课程为:

 [DataContract(Namespace =   http://www.abcdefg.com)] 
internal class 记录
{
私人 double n1;
private BitmapImage bimg;

内部记录( double n1,BitmapImage bimg)
{
this .n1 = n1;
.bimg = bimg;
}
[DataMember]
internal BitmapImage image
{
获取 {返回 bimg; }
set {bimg = value ; }
}

[DataMember]
内部 double OperandNumberOne
{
get { return n1; }
set {n1 = value ; }
}

public 覆盖 string ToString()
{
return string .Format( 记录:{0}和图像:{1},n1,bimg的ToString());
}
}





和序列化在这里完成:



  private   async   void  save_Click( object  sender,RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
openPicker.FileTypeFilter.Add( 。jpg);
StorageFile file = await openPicker.PickSingleFileAsync();
IRandomAccessStream imageStream = await file.OpenReadAsync();
bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream);
ImgUIelement.Source = bitmapImage;


MemoryStream stream1 = new MemoryStream();
// 使用DataContractSerializer将Record对象序列化为内存流。
DataContractSerializer serializer = new DataContractSerializer( typeof (Record));
记录record1 = new 记录( 1 ,bitmapImage);
serializer.WriteObject(stream1,record1); // EXCEPTION HERE

tbx_OP.Text = 写入流: + record1.ToString();

FileSavePicker fileSavePicker = new FileSavePicker();
fileSavePicker.DefaultFileExtension = 。bla;
fileSavePicker.FileTypeChoices.Add( Bla Files new List< string> { 。bla});
fileSavePicker.SuggestedFileName = 新Bla文件;
fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
var sfile = await fileSavePicker.PickSaveFileAsync();

使用(Stream x = await sfile.OpenStreamForWriteAsync())
{
x.Seek( 0 ,SeekOrigin.Begin);
stream1.WriteTo(x);
}
}
< / string >





我的要求是序列化一个包含图像列表和列表的对象StorageFiles到我的Windows应用商店应用程序中的文件。我试图找出是否有可能序列化单个图像。

如果可能,任何人都可以提供类似这样的类的示例代码..

公共类ExClass 
{
列表< 图像 > imgList = new List < Image > ();
列表< StorageFile > audList = new List < StorageFile > < /跨度>();
}





我没有找到任何序列化除了字符串,Int,Double ... Primitive之外的类型的示例的。


(Windows 8 Apps, C#)
Hi,
I have a number of Images(.jpg) and Audio-files(.mp3) in each object. I would like to store these objects in separate files and retrieve the content later. I searched for Object Serialization, but could not find a right example for Windows 8 apps.
So, what are the ways of saving the objects to files in Windows 8 apps(C#).
If it is Object Serialization, please give a sample piece of code or a link to it.

解决方案

Please see my comment to the question.

The best method is perhaps the Data Contract:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

Please see my past answers where I advocate this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deseralize a json string array[^].

The answers are related to .NET, highly recommended. If you don''t use any .NET languages, please don''t blame me: you did not even mention the language you are using.

For C++ (not C++/CLI), for example, I would recommend to look for boost serialization: http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html[^].

—SA


Quote:

So, what are the ways of saving the objects to files in Windows 8 apps(C#).


Have a look at this Tip:
Windows 8 App - Data storage in files using Windows.Storage namespace[^]


I am getting an Exception:
An exception of type ''System.Runtime.Serialization.InvalidDataContractException'' occurred in System.Runtime.Serialization.dll but was not handled in user code

Additional information: Type ''Windows.UI.Xaml.Media.ImageSource'' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

at serializer.WriteObject(stream1, record1)

The class is:

[DataContract(Namespace = "http://www.abcdefg.com")]
    internal class Record
    {
        private double n1;
        private BitmapImage bimg;

        internal Record(double n1, BitmapImage bimg)
        {
            this.n1 = n1;
            this.bimg = bimg;
        }
        [DataMember]
        internal BitmapImage image
        {
            get { return bimg; }
            set { bimg = value; }
        }

        [DataMember]
        internal double OperandNumberOne
        {
            get { return n1; }
            set { n1 = value; }
        }

        public override string ToString()
        {
            return string.Format("Record: {0} and an image: {1}", n1, bimg.ToString());
        }
    }



and the Serialization is done here:

private async void save_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            openPicker.FileTypeFilter.Add(".jpg");
            StorageFile file = await openPicker.PickSingleFileAsync();
            IRandomAccessStream imageStream = await file.OpenReadAsync();
            bitmapImage = new BitmapImage();
            bitmapImage.SetSource(imageStream);
            ImgUIelement.Source= bitmapImage;

            
            MemoryStream stream1 = new MemoryStream();
            //Serialize the Record object to a memory stream using DataContractSerializer.
            DataContractSerializer serializer = new DataContractSerializer(typeof(Record));
            Record record1 = new Record(1, bitmapImage);
            serializer.WriteObject(stream1, record1);   // EXCEPTION HERE

            tbx_OP.Text = "Written to Stream:" + record1.ToString();

            FileSavePicker fileSavePicker = new FileSavePicker();
            fileSavePicker.DefaultFileExtension = ".bla";
            fileSavePicker.FileTypeChoices.Add("Bla Files", new List<string> { ".bla" });
            fileSavePicker.SuggestedFileName = "New Bla File";
            fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            var sfile = await fileSavePicker.PickSaveFileAsync();

            using (Stream x = await sfile.OpenStreamForWriteAsync())
            {
                x.Seek(0, SeekOrigin.Begin);
                stream1.WriteTo(x);
            }
}
</string>



My requirement is to serialize an object consisting a List of Images and List of StorageFiles into a File, in my Windows Store App. I am trying to find intially whether it is possible to serialize a Single Image.
If possible could anyone please provide the sample code for a class like this..

public class ExClass
{
    List<Image> imgList = new List<Image>();
    List<StorageFile> audList = new List<StorageFile>();
}



I did''nt find any examples for serializing Types other than the Strings,Int,Double..Primitive ones.


这篇关于将对象存储到Windows 8应用程序中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆