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


C# DataContractSerializer.ReadObject方法代码示例

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


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

示例1: Translate

        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
开发者ID:rhysgodfrey,项目名称:Trosi,代码行数:31,代码来源:Translator.cs

示例2: Main

        static void Main(string[] args)
        {
            Person p = new Person() { Name = "曾小丹", Age = 18 };
            var ds = new DataContractSerializer(typeof(Person));
            var s = new MemoryStream();
            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(s))
            {
                ds.WriteObject(w, p);
            }

            var s2 = new MemoryStream(s.ToArray());
            Person p2;
            using (XmlDictionaryReader r = XmlDictionaryReader.CreateBinaryReader(s2, XmlDictionaryReaderQuotas.Max))
            {
                p2 = (Person)ds.ReadObject(r);
            }
            //XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
            //using (XmlWriter w = XmlWriter.Create(@"D:\WebPage\Img\perosn.xml", settings))
            //{
            //    ds.WriteObject(w, p);
            //}
            System.Diagnostics.Process.Start(@"D:\WebPage\Img\perosn.xml");
            // 使用程序打开该文件?!
            //using (Stream s = File.Create(@"D:\WebPage\Img\perosn.xml"))
            //{
            //    ds.WriteObject(s, p);
            //}

            Person p2;
            using (Stream s = File.OpenRead(@"D:\WebPage\Img\perosn.xml"))
            {
                p2 = (Person)ds.ReadObject(s);
            }
            Console.WriteLine(p2.Name + "" + p2.Age);
        }
开发者ID:ZLLselfRedeem,项目名称:zllinmitu,代码行数:35,代码来源:Program.cs

示例3: DesignUnitInfoRepository

        public DesignUnitInfoRepository()
        {
            var ser = new DataContractSerializer(typeof(UnitesInfo));

            natoList = new SortedList<ushort, UnitInfo>();

            // TODO find a better way to design time this
            using ( var reader = new FileStream(Path.Combine(@"F:\Dev\RedReplay\RedReplay\Release", "NATO.xml"), FileMode.Open) )
            {
                UnitesInfo natoUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in natoUnits )
                {
                    natoList.Add(unit.ShowRoomID, unit);
                }
            }

            pactList = new SortedList<ushort, UnitInfo>();

            // TODO find a better way to design time this
            using ( var reader = new FileStream(Path.Combine(@"F:\Dev\RedReplay\RedReplay\Release", "PACT.xml"), FileMode.Open) )
            {
                UnitesInfo pactUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in pactUnits )
                {
                    pactList.Add(unit.ShowRoomID, unit);
                }
            }
        }
开发者ID:RemiGC,项目名称:RReplay,代码行数:30,代码来源:DesignUnitInfoRepository.cs

示例4: UnitInfoRepository

        public UnitInfoRepository()
        {
            var ser = new DataContractSerializer(typeof(UnitesInfo));

            natoList = new SortedList<ushort, UnitInfo>();

            using ( var reader = new FileStream(Path.Combine(Settings.Default.exeFolder, "NATO.xml"), FileMode.Open) )
            {
                UnitesInfo natoUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in natoUnits )
                {
                    natoList.Add(unit.ShowRoomID, unit);
                }
            }

            pactList = new SortedList<ushort, UnitInfo>();

            using ( var reader = new FileStream(Path.Combine(Settings.Default.exeFolder, "PACT.xml"), FileMode.Open) )
            {
                UnitesInfo pactUnits = ser.ReadObject(reader) as UnitesInfo;

                foreach ( var unit in pactUnits)
                {
                    pactList.Add(unit.ShowRoomID, unit);
                }
            }
        }
开发者ID:RemiGC,项目名称:RReplay,代码行数:28,代码来源:UnitInfoRepository.cs

示例5: Main

        static void Main(string[] args)
        {
            /* Data contract serialization typically reads and writes XML data. You use a
             * DataContractSerializer object for data contract serialization. Its 
             * WriteObject() method can write to a stream, or it can write to an object that
             * extends XmlDictionaryWriter, an abstract class that controls XML output and 
             * can be extended to change the way the XML output is written. Objects are
             * deserialized using the ReadObject() method, which can read XML data from
             * a stream or an XmlDictionaryReader.
             */
            DataContractSerializer serializer = new DataContractSerializer(typeof(SerializableGuy));

            // We’ll create a new SerializableGuy object and serialize it using a FileStream.
            SerializableGuy guyToWrite = new SerializableGuy("Joe", 37, 150);
            using (FileStream writer = new FileStream("serialized_guy.xml", FileMode.Create))
            {
                serializer.WriteObject(writer, guyToWrite);
            }

            // We can open the file we just wrote and deserialize it into a new guy using ReadObject().
            // We’ll use the XmlDictionaryReader.CreateTextReader() method to create an object that
            // reads XML data from a stream. 
            SerializableGuy guyToRead = null;
            using (FileStream inputStream = new FileStream("serialized_guy.xml", FileMode.Open))
            using (XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(inputStream, new XmlDictionaryReaderQuotas()))
            {
                guyToRead = serializer.ReadObject(reader, true) as SerializableGuy;
            }
            Console.WriteLine(guyToRead);
            // Output: Joe is 37 years old and has 150 bucks [1461194451,0]


            string xmlGuy = @"
<Guy xmlns=""http://www.headfirstlabs.com"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
   <Age>43</Age> 
   <Cash>225</Cash> 
   <Name>Bob</Name> 
   <secretNumberOne>54321</secretNumberOne>
</Guy>";
            byte[] buffer = UnicodeEncoding.UTF8.GetBytes(xmlGuy);

            using (XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(buffer, new XmlDictionaryReaderQuotas()))
            {
                guyToRead = serializer.ReadObject(reader, true) as SerializableGuy;
            }
            Console.WriteLine(guyToRead);
            // Output: Bob is 43 years old and has 225 bucks [54321,0]

            Console.ReadKey();
        }
开发者ID:HeberAlvarez,项目名称:HeadFirst,代码行数:52,代码来源:Program.cs

示例6: Load

 public static void Load()
 {
     DataContractSerializer dcs = new DataContractSerializer(typeof(TagDB));
     XmlReader xmlr = XmlReader.Create("TagDBase.xml");
     dcs.ReadObject(xmlr);
     xmlr.Close();
 }
开发者ID:choob207,项目名称:fivetasks,代码行数:7,代码来源:TaskTagDB.cs

示例7: Client_writeToFileTest

        public void Client_writeToFileTest()
        {
            Client testUser = new Client("testUser","5555");

            testUser.writeToFile();

            #region ReadClientObjectFromFile

                string pathToDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string USER_LOCATION = "\\users\\";
                string XML_EXT = ".xml";
                string writePath = pathToDir + USER_LOCATION + testUser.Name + XML_EXT;

            Client tempObj;

            //Reads from the xml file for the client.
            using (FileStream reader = new FileStream(writePath, FileMode.Open, FileAccess.Read))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Client));
                tempObj = (Client)ser.ReadObject(reader);
            }

            Assert.AreEqual(testUser.Name, tempObj.Name);
            Assert.AreEqual(testUser.Online, tempObj.Online);
            Assert.AreEqual(testUser.Password, tempObj.Password);

            #endregion
        }
开发者ID:patdGitHub,项目名称:Real-Time-Server-Connected-Code-Editor,代码行数:28,代码来源:ClientTests.cs

示例8: OnTranslateButtonClicked

    protected void OnTranslateButtonClicked(object sender, EventArgs e)
    {
        string fromText = fromTextInput.Buffer.Text;
        string toText = "";

        AdmAuthentication admAuth = new AdmAuthentication("", "");
        AdmAccessToken admToken = admAuth.GetAccessToken();

        string encodedFromText = System.Web.HttpUtility.UrlEncode(fromText);
        string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(fromText) + "&from=" + "en" + "&to=" + "ru";
        string authToken = "Bearer" + " " + admToken.access_token;

        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpWebRequest.Headers.Add("Authorization", authToken);

        WebResponse response = httpWebRequest.GetResponse();
        //		try
        //		{
            response = httpWebRequest.GetResponse();
            using (Stream stream = response.GetResponseStream())
            {
            System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(System.Type.GetType("System.String"));
                toText = (string)dcs.ReadObject(stream);
            }
        //		}

        toTextInput.Buffer.Text = toText;
    }
开发者ID:randaalex,项目名称:tranlsator,代码行数:28,代码来源:MainWindow.cs

示例9: LoadMemberList

        //Methods
        public MemberList LoadMemberList()
        {
            try
            {
                MemberList loaded = null;

                if (System.IO.File.Exists(this.fullFilePath))
                {
                    using (FileStream readFileStream = new FileStream(this.fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        DataContractSerializer deserializer = new DataContractSerializer(typeof(MemberList));
                        loaded = (MemberList)deserializer.ReadObject(readFileStream);
                    }

                    if (loaded != null)
                    {
                        //setup subscriptions
                        loaded.SetupSubscriptions();
                    }

                    return loaded;
                }
            }
            catch { }

            return null;
        }
开发者ID:of222au,项目名称:1DV607-Objektorienterad-analys-och-design-med-UML,代码行数:28,代码来源:Storage.cs

示例10: GetBenutzer

 private List<Benutzer> GetBenutzer()
 {
     HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri + "benutzer/");
     webrequest.Method = "GET";
     HttpWebResponse webresponse = null;
     try
     {
         webresponse = (HttpWebResponse)webrequest.GetResponse();
         HttpStatusCode rc = webresponse.StatusCode;
         DataContractSerializer serl = new DataContractSerializer(typeof(List<Benutzer>));
         return (List<Benutzer>)serl.ReadObject(webresponse.GetResponseStream());
     }
     catch (WebException we)
     {
         if (we.Response != null)
         {
             webresponse = (HttpWebResponse)we.Response;
             MessageBox.Show(webresponse.StatusDescription + "!", "Fehler");
         }
         else
         {
             MessageBox.Show("Server nicht erreichbar!", "Fehler");
         }
         return new List<Benutzer>();
     }
     finally
     {
         if (webresponse != null)
             webresponse.Close();
     }
 }
开发者ID:Golgoin,项目名称:ProjektarbeitVokabeltrainer,代码行数:31,代码来源:Start.xaml.cs

示例11: Main

        static void Main()
        {
            Record record1 = new Record(1, 2, "+", 3);
            Console.WriteLine("Original record: {0}", record1.ToString());

            MemoryStream stream1 = new MemoryStream();

            //Serialize the Record object to a memory stream using DataContractSerializer.
            System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Record));
            serializer.WriteObject(stream1, record1);

            stream1.Position = 0;

            //Deserialize the Record object back into a new record object
            Record record2 = (Record)serializer.ReadObject(stream1);

            Console.WriteLine("Deserialized record: {0}", record2.ToString());

            MemoryStream stream2 = new MemoryStream();

            XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);
            serializer.WriteObject(binaryDictionaryWriter, record1);
            binaryDictionaryWriter.Flush();

            //report the length of the streams
            Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
            Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:32,代码来源:client.cs

示例12: LoadFromFile

        public static object LoadFromFile(string fileName, Type t)
        {
            object o = null;
            try
            {
                byte[] fileContents = File.ReadAllBytes(fileName);

                byte[] decryptedData = Encryption.DecryptData(fileContents);

                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(decryptedData, 0, decryptedData.Length);

                    stream.Position = 0;

                    DataContractSerializer serializer = new DataContractSerializer(t);

                    o = serializer.ReadObject(stream);
                }
            }
            catch (Exception ex)
            {
            }
            return o;
        }
开发者ID:nirvash,项目名称:MtgoxTrader,代码行数:25,代码来源:Utils.cs

示例13: Data_contract_serialization_will_change_the_type_of_a_collection

        public void Data_contract_serialization_will_change_the_type_of_a_collection()
        {
            using (var session = DataAccess.OpenSession())
            {
                var forum = session.Get<ForumModel>(1);

            Assert.AreEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());

            var knownTypes = new List<Type>
                                 {
                                     typeof (TopicModel),
                                     typeof (NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>),
                                     typeof (NHibernate.Impl.CollectionFilterImpl)
                                 };
                var serializer = new   DataContractSerializer(typeof(ForumModel), knownTypes);

            //serialize company to a memory stream
            Stream stream = new MemoryStream();
            serializer.WriteObject(stream, forum);
            Console.WriteLine();
            //deserialize the memory stream back to a company
            stream.Position = 0;
            forum = (ForumModel)serializer.ReadObject(stream);

            Assert.AreNotEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());
            Assert.AreEqual(typeof(TopicModel[]), forum.Topics.GetType());
            }
        }
开发者ID:michal-franc,项目名称:ElearnServices,代码行数:28,代码来源:DataSerializationTests.cs

示例14: RestoreAsync

        public static async Task RestoreAsync()
        {
            _sessionState = new Dictionary<String, Object>();

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                    _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
                }

                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        frame.ClearValue(FrameSessionStateProperty);
                        RestoreFrameNavigationState(frame);
                    }
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
开发者ID:scubism,项目名称:OrangeWinRT,代码行数:28,代码来源:SuspensionManager.cs

示例15: RequiredDataIsProvided_AndModelIsBound_NoValidationErrors

        public async Task RequiredDataIsProvided_AndModelIsBound_NoValidationErrors()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml-dcs"));
            var input = "<Store xmlns=\"http://schemas.datacontract.org/2004/07/XmlFormattersWebSite\" " +
                        "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Address><State>WA</State><Zipcode>" +
                        "98052</Zipcode></Address><Id>10</Id></Store>";
            var content = new StringContent(input, Encoding.UTF8, "application/xml-dcs");

            // Act
            var response = await client.PostAsync("http://localhost/Validation/CreateStore", content);

            //Assert
            var dcsSerializer = new DataContractSerializer(typeof(ModelBindingInfo));
            var responseStream = await response.Content.ReadAsStreamAsync();
            var modelBindingInfo = dcsSerializer.ReadObject(responseStream) as ModelBindingInfo;
            Assert.NotNull(modelBindingInfo);
            Assert.NotNull(modelBindingInfo.Store);
            Assert.Equal(10, modelBindingInfo.Store.Id);
            Assert.NotNull(modelBindingInfo.Store.Address);
            Assert.Equal(98052, modelBindingInfo.Store.Address.Zipcode);
            Assert.Equal("WA", modelBindingInfo.Store.Address.State);
            Assert.Empty(modelBindingInfo.ModelStateErrorMessages);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:26,代码来源:XmlDataContractSerializerInputFormatterTest.cs


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