当前位置: 首页>>代码示例>>C#>>正文


C# System.Runtime.Serialization.DataContractSerializer.WriteObject方法代码示例

本文整理汇总了C#中System.Runtime.Serialization.DataContractSerializer.WriteObject方法的典型用法代码示例。如果您正苦于以下问题:C# System.Runtime.Serialization.DataContractSerializer.WriteObject方法的具体用法?C# System.Runtime.Serialization.DataContractSerializer.WriteObject怎么用?C# System.Runtime.Serialization.DataContractSerializer.WriteObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Runtime.Serialization.DataContractSerializer的用法示例。


在下文中一共展示了System.Runtime.Serialization.DataContractSerializer.WriteObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetXml

 internal static string GetXml(object o) {
   var formatter = new System.Runtime.Serialization.DataContractSerializer(o.GetType());
   using (var stringWriter = new StringWriter())
   using (var xmlWriter = new XmlTextWriter(stringWriter)) {
     xmlWriter.Formatting = Formatting.Indented;
     xmlWriter.QuoteChar = '\'';
     formatter.WriteObject(xmlWriter, o);
     return stringWriter.ToString();
   }
 }
开发者ID:Prover,项目名称:Prover.SpecWriter,代码行数:10,代码来源:DataContractFormatter.cs

示例2: using

 /// <summary>
 /// Creates a new object that is a copy of the current instance.
 /// </summary>
 /// <returns>
 /// A new object that is a copy of this instance.
 /// </returns>
 object ICloneable.Clone()
 {
     var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
     using (var ms = new System.IO.MemoryStream())
     {
         serializer.WriteObject(ms, this);
         ms.Position = 0;
         return serializer.ReadObject(ms);
     }
 }
开发者ID:Tony-Liang,项目名称:RBAC,代码行数:16,代码来源:EntityBase.cs

示例3: TestSer

        public void TestSer()
        {
            var f = new SomeTestingViewModel() {  Result="hahahaha"};

            var dx = new System.Runtime.Serialization.DataContractSerializer(typeof(SomeTestingViewModel));
            var s = new MemoryStream();
            dx.WriteObject(s, f);
            s.Position = 0;
            var s2 = dx.ReadObject(s) as SomeTestingViewModel;
            Assert.AreEqual(s2.Result, f.Result);
        }
开发者ID:taojunfeng,项目名称:MVVM-Sidekick,代码行数:11,代码来源:SerTest.cs

示例4: ToBinary

 /// <summary>
 /// Returns a byte array that represents the current <see cref="T:System.Object"/>. 
 /// </summary>
 /// <returns>A byte array that represents the current <see cref="T:System.Object"/>.</returns>
 public virtual byte[] ToBinary()
 {
     byte[] buffer;
     using (var ms = new System.IO.MemoryStream())
     using (var writer = System.Xml.XmlDictionaryWriter.CreateBinaryWriter(ms))
     {
         var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
         serializer.WriteObject(writer, this);
         writer.Flush();
         buffer = ms.ToArray();
     }
     return buffer;
 }
开发者ID:Tony-Liang,项目名称:RBAC,代码行数:17,代码来源:EntityBase.cs

示例5: GetLanguageNames

        public static string[] GetLanguageNames(string[] languageCodes)
        {
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/GetLanguageNames?locale=" + languageCodes[0] + "&appId=" + appId;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.ContentType = "text/xml";
            httpWebRequest.Method = "POST";
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String[]"));
            using (System.IO.Stream stream = httpWebRequest.GetRequestStream())
            {
                dcs.WriteObject(stream, languageCodes);
            }

            WebResponse response = null;
            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    return (string[])dcs.ReadObject(stream);
                }
            }
            catch (WebException)
            {
                if (languageCodes.Length == 1 && languageCodes[0] == "en")
                    return new string[] { "English" };
                else
                    throw;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }
开发者ID:cchitsiang,项目名称:Multi-Lingual-Chat,代码行数:41,代码来源:BingServicesClient.cs

示例6: Serialize

        public string Serialize(object serializableObject)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(serializableObject.GetType(),
                                                                                         null,
                                                                                         Int32.MaxValue,
                                                                                         false,
                                                                                         false,
                                                                                         null,
                                                                                         _dataContractResolver);

                serializer.WriteObject(memoryStream, serializableObject);
                memoryStream.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memoryStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
开发者ID:AtmosphereMessaging,项目名称:Cumulus,代码行数:21,代码来源:DataContractSerializer.cs

示例7: DataContractSerialize

        public static string DataContractSerialize(Object obj, bool compress)
        {
            if (obj != null)
            {
                Type objType = obj.GetType();
                System.Runtime.Serialization.DataContractSerializer aa = new System.Runtime.Serialization.DataContractSerializer(objType);
                StringBuilder sb = new StringBuilder();

                // Inserisce l'assembly qualified name nello stream del buffer come primo elemento separato dalla @
                sb.Append(objType.AssemblyQualifiedName);
                sb.Append('@');

                XmlWriter writer = XmlWriter.Create(sb);
                aa.WriteObject(writer, obj);
                writer.Close();

                return sb.ToString();
            }
            else
                return null;
        }
开发者ID:shelgaerel,项目名称:MobileApplication,代码行数:21,代码来源:Utility.cs

示例8: OnSaveAs

        private void OnSaveAs(object sender, ExecuteEventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Filter = "Shader file (*.sh)|*.sh|All files (*.*)|*.*";
                dialog.FilterIndex = 0;
                dialog.RestoreDirectory = true;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    using (var stream = dialog.OpenFile())
                    {
                        using (var xmlStream = new System.IO.MemoryStream())
                        {
                            var nodeGraph = ModelConversion.ToShaderPatcherLayer(graphControl);
                            var serializer = new System.Runtime.Serialization.DataContractSerializer(
                                typeof(ShaderPatcherLayer.NodeGraph));
                            var settings = new System.Xml.XmlWriterSettings()
                            {
                                Indent = true,
                                IndentChars = "\t",
                                Encoding = System.Text.Encoding.ASCII
                            };

                                // write the xml to a memory stream to begin with
                            using (var writer = System.Xml.XmlWriter.Create(xmlStream, settings))
                            {
                                serializer.WriteObject(writer, nodeGraph);
                            }

                                // we hide the memory stream within a comment, and write
                                // out a hlsl shader file
                                // The HLSL compiler doesn't like UTF files... It just wants plain ASCII encoding

                            using (var sw = new System.IO.StreamWriter(stream, System.Text.Encoding.ASCII))
                            {
                                var shader = ShaderPatcherLayer.NodeGraph.GenerateShader(nodeGraph, System.IO.Path.GetFileNameWithoutExtension(dialog.FileName));
                                sw.Write(shader);

                                sw.Write("/* **** **** NodeEditor **** **** \r\nNEStart{");
                                sw.Flush();
                                xmlStream.WriteTo(stream);
                                sw.Write("}NEEnd\r\n **** **** */\r\n");
                            }

                        }
                    }
                }
            }
        }
开发者ID:ldh9451,项目名称:XLE,代码行数:50,代码来源:ExampleForm.cs

示例9: ToXml

        /// <summary>
        /// Returns an XML <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. 
        /// </summary>
        /// <returns>An XML <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.</returns>
        public virtual string ToXml()
        {
            var settings = new System.Xml.XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new System.Text.StringBuilder();
            using (var writer = System.Xml.XmlWriter.Create(sb, settings))
            {
                var serializer = new System.Runtime.Serialization.DataContractSerializer(GetType());
                serializer.WriteObject(writer, this);
                writer.Flush();
            }

            return sb.ToString();
        }
开发者ID:Tony-Liang,项目名称:RBAC,代码行数:20,代码来源:EntityBase.cs

示例10: EditSlide

        public void EditSlide(PresentationInfo info, Slide slide)
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE");
            if (key != null)
            {
                key = key.OpenSubKey("PolyMedia");
                if (key != null)
                {
                    key = key.OpenSubKey("PresentationDesigner");
                    if (key != null)
                    {
                        String path = key.GetValue("ExePath").ToString();
                        UserIdentity id = (UserIdentity)System.Threading.Thread.CurrentPrincipal;
                        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(UserIdentity));
                        System.IO.MemoryStream stream = new System.IO.MemoryStream();
                        ser.WriteObject(stream, id);
                        stream.Seek(0, System.IO.SeekOrigin.Begin);
                        String args = String.Format("{0} {1} \"{2}\"", info.UniqueName, slide.Id, new System.IO.StreamReader(stream).ReadToEnd().Replace('\"', '\''));

                        System.Diagnostics.Process.Start(path, args);
                        return;
                    }
                }
            }
            MessageBoxAdv.Show("Не удается найти путь запуска модуля подготовки сценариев!", "Редакитрование сцены");
        }
开发者ID:AlexSneg,项目名称:VIRD-1.0,代码行数:26,代码来源:PlayerController.cs

示例11: SaveMediaFilesAsync

        async private Task SaveMediaFilesAsync()
        {
            string fullPath = "mediafiles.xml";
            try
            { 
                Windows.Storage.StorageFile file;
                bool bRes = await DeleteFile(fullPath);
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fullPath);
                if (file != null)
                {
                    using (var stream = await file.OpenStreamForWriteAsync())
                    {
                        if (stream != null)
                        {
                            System.Runtime.Serialization.DataContractSerializer sessionSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Dictionary<string, MediaLibraryItem>));
                            sessionSerializer.WriteObject(stream, defaultMediaDictionary);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogMessage("Exception while saving mediafiles:" + e.Message);
            }

        }
开发者ID:flecoqui,项目名称:Windows10,代码行数:26,代码来源:MainPage.xaml.cs

示例12: InternalSaveSnapshotAsync

        internal async Task InternalSaveSnapshotAsync(IPicLibFolder[] folders)
        {
            var sl = new System.Runtime.Serialization.DataContractSerializer(typeof(PicLibFolder[]));

            var ms = new MemoryStream();
            sl.WriteObject(ms, folders.OfType<PicLibFolder>().ToArray());
            ms.Position = 0;
            GetCacheFile(CreationCollisionOption.ReplaceExisting);
            var f = await workingFile;
            using (var ws = await f.OpenStreamForWriteAsync())
            {
                await ms.CopyToAsync(ws);
            }


        }
开发者ID:waynebaby,项目名称:GreaterShareUWP,代码行数:16,代码来源:PicLibFolderScanService.cs

示例13: Serialize

 public override void Serialize(Stream stream, object obj)
 {
     var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
     serializer.WriteObject(stream, obj);
 }
开发者ID:rabitarochan,项目名称:LightNode,代码行数:5,代码来源:StandardContentFormatters.cs

示例14: BuildMeta

        public static RuntimeTypeModel BuildMeta()
        {
            
            RuntimeTypeModel model;
#if !FX11
            model = TypeModel.Create();
            model.Add(typeof(Order), false)
                .Add(1, "OrderID")
                .Add(2, "CustomerID")
                .Add(3, "EmployeeID")
                .Add(4, "OrderDate")
                .Add(5, "RequiredDate")
                .Add(6, "ShippedDate")
                .Add(7, "ShipVia")
                .Add(8, "Freight")
                .Add(9, "ShipName")
                .Add(10, "ShipAddress")
                .Add(11, "ShipCity")
                .Add(12, "ShipRegion")
                .Add(13, "ShipPostalCode")
                .Add(14, "ShipCountry");
            model.Add(typeof(Product), false)
                .Add(1, "ProductID")
                .Add(2, "ProductName")
                .Add(3, "SupplierID")
                .Add(4, "CategoryID")
                .Add(5, "QuantityPerUnit")
                .Add(6, "UnitPrice")
                .Add(7, "UnitsInStock")
                .Add(8, "UnitsOnOrder")
                .Add(9, "ReorderLevel")
                .Add(10, "Discontinued")
                .Add(11, "LastEditDate")
                .Add(12, "CreationDate");

            TypeModel compiled = model.Compile();
            Type type = typeof(Product);
            PropertyInfo[] props = type.GetProperties();

            Product prod = new Product();
            prod.ProductID = 123;
            prod.ProductName = "abc devil";
            prod.SupplierID = 456;
            prod.CategoryID = 13;
            prod.QuantityPerUnit = "1";
            prod.UnitPrice = 12.99M;
            prod.UnitsInStock = 96;
            prod.UnitsOnOrder = 12;
            prod.ReorderLevel = 30;
            prod.Discontinued = false;
            prod.LastEditDate = new DateTime(2009, 5, 7);
            prod.CreationDate = new DateTime(2009, 1, 3);

            DumpObject("Original", props, prod);
            
            const int loop = 100000;
            Console.WriteLine("Iterations: " + loop);
            Stopwatch watch;
            MemoryStream reuseDump = new MemoryStream(100 * 1024);
#if FX30
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(type);
            
            using (MemoryStream ms = new MemoryStream()) {
                dcs.WriteObject(ms, prod);
                Console.WriteLine("DataContractSerializer: {0} bytes", ms.Length);
            }
            
            watch = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                reuseDump.SetLength(0);
                dcs.WriteObject(reuseDump, prod);                
            }
            watch.Stop();
            Console.WriteLine("DataContractSerializer serialize: {0} ms", watch.ElapsedMilliseconds);
            watch = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                reuseDump.Position = 0;
                dcs.ReadObject(reuseDump);
            }
            watch.Stop();
            Console.WriteLine("DataContractSerializer deserialize: {0} ms", watch.ElapsedMilliseconds);

            {
            reuseDump.Position = 0;
            Product p1 = (Product) dcs.ReadObject(reuseDump);
            DumpObject("DataContractSerializer", props, p1);
            }

            System.Runtime.Serialization.NetDataContractSerializer ndcs = new System.Runtime.Serialization.NetDataContractSerializer();
            
            using (MemoryStream ms = new MemoryStream()) {
                ndcs.Serialize(ms, prod);
                Console.WriteLine("NetDataContractSerializer: {0} bytes", ms.Length);
            }
            
            watch = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
//.........这里部分代码省略.........
开发者ID:XewTurquish,项目名称:vsminecraft,代码行数:101,代码来源:Program.cs

示例15: SaveManifest

        /// <summary>
        /// SaveManifest
        /// Save manifest on disk 
        /// </summary>
        public async Task<bool> SaveManifest(ManifestCache cache)
        {
            bool bResult = false;
            using (var releaser = await internalManifestDiskLock.WriterLockAsync())
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Writer Enter for Uri: " + cache.ManifestUri.ToString());
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        if (ms != null)
                        {
                            System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(ManifestCache));
                            ser.WriteObject(ms, cache);
                            bResult = await Save(Path.Combine(Path.Combine(root, cache.StoragePath), manifestFileName), ms.ToArray());
                        }
                    }
                }
                catch(Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Writer exception for Uri: " + cache.ManifestUri.ToString() + " Exception: " + e.Message);

                }
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " internalManifestDiskLock Writer Exit for Uri: " + cache.ManifestUri.ToString());
            }
            return bResult;
        }
开发者ID:flecoqui,项目名称:Windows10,代码行数:31,代码来源:DiskCache.cs


注:本文中的System.Runtime.Serialization.DataContractSerializer.WriteObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。