/// <summary>
        ///  Write this IBinarySerializable item in binary format to a file with the given path.
        ///  The file will be replaced if it exists already.
        /// </summary>
        /// <param name="item">Item to write</param>
        /// <param name="filePath">File Path to write binary form of item to</param>
        public static void FileWrite(this IBinarySerializable item, string filePath)
        {
            // Ensure the containing folder exists
            string serializationDirectory = Path.GetDirectoryName(filePath);

            if (!String.IsNullOrEmpty(serializationDirectory))
            {
                Directory.CreateDirectory(serializationDirectory);
            }

            // Serialize the item
            long       lengthWritten = 0;
            FileStream s             = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Delete);

            using (BinaryWriter writer = new BinaryWriter(s))
            {
                item.WriteBinary(writer);
                lengthWritten = s.Position;
            }

            // If nothing was written, delete the file
            if (lengthWritten == 0)
            {
                File.Delete(filePath);
            }
        }
Exemplo n.º 2
0
        public static void Write(this IBinarySerializable item, string filePath)
        {
            string fullPath = FullPath(filePath);

            // Ensure the containing folder exists
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

            // Serialize (to a '.new' file)
            using (SerializationContext context = new SerializationContext(new FileStream(fullPath + ".new", FileMode.Create, FileAccess.Write, FileShare.Delete)))
            {
                item.WriteBinary(context);
            }

            // Overwrite the base file semi-atomically (if file exists, it's fully written)
            FileIO.Replace(fullPath + ".new", fullPath);
        }