예제 #1
0
        /// <exception cref="FileLockedException"></exception>
        protected XmlFileManager(string path, string rootTag, bool readOnly)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            if (string.IsNullOrEmpty(rootTag))
            {
                throw new ArgumentNullException("rootTag");
            }

            FilePath = path;

            // make sure the folder exists
            string folder = Path.GetDirectoryName(FilePath);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            // open/create the file
            try
            {
                _file = File.Open(FilePath, FileMode.OpenOrCreate,
                                  readOnly ? FileAccess.Read : FileAccess.ReadWrite,
                                  readOnly ? FileShare.ReadWrite : FileShare.Read);
            }
            catch (IOException e)
            {
                throw new FileLockedException(FilePath, e);
            }

            // parse it
            var document = new XDocument();

            try
            {
                using (var fileLock = new FileLock(_file))
                {
                    if (_file.Length > 0)
                    {
                        document = XDocument.Load(_file);
                    }
                    else                     // initialize the XML document with the root element
                    {
                        document = new XDocument(new XElement(rootTag));
                    }
                }
            }
            catch (FileLockedException)
            {
                Dispose();
                throw;
            }
            catch (Exception e)
            {
                Dispose();
                throw new InvalidDataException(string.Format("{0} is corrupt.", PathHelper.Quote(FilePath)), e);
            }

            RootElement = document.Root;

            if (readOnly)
            {
                Dispose();
            }
        }