示例#1
0
        Database TryLoad(MemoryStream databaseStream)
        {
            //create a copy of the stream so we can try again if we get an exception which indicates we should change parameters
            //This is not optimal in terms of (short-time) memory usage but is hard to avoid because the Keepass library closes streams also in case of errors.
            //Alternatives would involve increased traffic (if file is on remote) and slower loading times, so this seems to be the best choice.
            MemoryStream workingCopy = new MemoryStream();

            databaseStream.CopyTo(workingCopy);
            workingCopy.Seek(0, SeekOrigin.Begin);
            //reset stream if we need to reuse it later:
            databaseStream.Seek(0, SeekOrigin.Begin);
            //now let's go:
            try
            {
                Database newDb = _app.LoadDatabase(_ioc, workingCopy, _compositeKey, StatusLogger, _format);
                Kp2aLog.Log("LoadDB OK");

                //make sure the stored access time for the actual file is more recent than that of its backup
                Thread.Sleep(10);
                SaveFileData(_ioc, _keyfileOrProvider);

                Finish(true, _format.SuccessMessage);
                return(newDb);
            }
            catch (OldFormatException)
            {
                _format = new KdbDatabaseFormat(_app);
                return(TryLoad(databaseStream));
            }
            catch (InvalidCompositeKeyException)
            {
                KcpPassword passwordKey = (KcpPassword)_compositeKey.GetUserKey(typeof(KcpPassword));

                if ((passwordKey != null) && (passwordKey.Password.ReadString() == "") && (_compositeKey.UserKeyCount > 1))
                {
                    //if we don't get a password, we don't know whether this means "empty password" or "no password"
                    //retry without password:
                    _compositeKey.RemoveUserKey(passwordKey);
                    //retry:
                    return(TryLoad(databaseStream));
                }
                else
                {
                    throw;
                }
            }
        }