none
Data written with DataContractSerialize not readable with DataContractSerialize RRS feed

  • Question

  • I'm getting an error reading a file with DataContractSerialize and I wrote with DataContractSerialize.  It seems to me that I should be able to read the same file that I'm saving, and for some reason I'm still getting the dreaded "the data at the root level is invalid line 1 position 1" error.  The ten postings I've read so far all seem to point to a malformed XML file.  What's confusing to me is that I've written the file with the same code that I'm not wanted to read it.

    OK.  I think I've got this reduced to a simple case as follows.

    Anyone know what the problem is?


        [Serializable]
        public class LoadSave
        {
            public Entry[] Entries;

            public LoadSave()
            {

            }

            private static void EnsureExists(string path)
            {
                string dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }

            public static LoadSave Load(string FileName)
            {
                LoadSave ret;
                EnsureExists(FileName);
                using (FileStream file = File.Open(FileName, FileMode.OpenOrCreate))
                {
                    file.Seek(0, SeekOrigin.Begin);
                    var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(LoadSave));
                    ret = (LoadSave) serializer.ReadObject(file);
                }
                return ret;
            }

            public static void Save(LoadSave ls, string FileName)
            {
                EnsureExists(FileName);
                using (FileStream file = File.Open(FileName, FileMode.OpenOrCreate))
                {
                    file.Seek(0, SeekOrigin.Begin);
                    var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(LoadSave));
                    serializer.WriteObject(file, ls);
                    file.Flush();
                }
            }
        }

    Friday, May 17, 2013 3:56 AM

Answers

  • Your code seems to work only for new or shorter files. Try this:

    public static void Save(LoadSave ls, string FileName)
    {
        EnsureExists(FileName);
        using (FileStream file = File.Open(FileName, FileMode.Create))
        {
            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(LoadSave));
            serializer.WriteObject(file, ls);
        }
    }

    Friday, May 17, 2013 5:55 AM