コード例 #1
0
        public MongoGridFSFileInfo GetFileById(string set_name, string fid)
        {
            MongoGridFSSettings mgfs = new MongoGridFSSettings();

            mgfs.Root = set_name;
            MongoGridFSFileInfo file_info = mdbs.GetGridFS(mgfs).FindOneById(new ObjectId(fid));

            return(file_info);
        }
コード例 #2
0
        internal MongoStorageFile(MongoGridFSFileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException("fileInfo");
            }

            this.fileInfo = fileInfo;
        }
コード例 #3
0
        public static FileModel FileModelFromGridFSMetadata(MongoGridFSFileInfo gfs_entry)
        {
            var file_model = new FileModel();

            file_model.Filename  = gfs_entry.Metadata["Filename"].AsString;
            file_model.PatientID = gfs_entry.Metadata["PatientID"].AsString;
            file_model.ID        = gfs_entry.Id.AsObjectId;

            return(file_model);
        }
コード例 #4
0
        private void InternalMoveFile(string fromVirtualPath, string destinationVirtualPath)
        {
            MongoGridFS mongoGridFs          = GetGridFS();
            string      fixedDestinationPath = FixPath(destinationVirtualPath);

            mongoGridFs.MoveTo(FixPath(fromVirtualPath), fixedDestinationPath);
            MongoGridFSFileInfo fileInfo = mongoGridFs.FindOne(fixedDestinationPath);

            mongoGridFs.SetMetadata(fileInfo, CreateMetadata(fixedDestinationPath, fileInfo.Metadata["is_directory"] == new BsonBoolean(true)));
        }
コード例 #5
0
        /// <summary>
        /// Gets a file contents by its Id. This is NOT to be used by the UI under any circumstances, UI should use the respective services
        /// that know how to apply proper access rules, etc.
        /// </summary>
        /// <param name="fileId">The ObjectId that represents the file to retrieve</param>
        /// <returns>A readable stream for the file.</returns>
        public static Stream ReadFileById(string fileId)
        {
            MongoGridFSFileInfo info = Files.GridFs.FindOneById(new BsonObjectId(new ObjectId(fileId)));

            if (!info.Exists)
            {
                throw new FileNotFoundException();
            }

            return(info.OpenRead());
        }
コード例 #6
0
        /// <summary>
        /// 下载指定标识的文件
        /// </summary>
        /// <param name="id">标识ObjectId</param>
        /// <param name="saveFile">保存文件路径</param>
        public void DownLoad(ObjectId id, string saveFile)
        {
            MongoGridFSFileInfo info = DataBase.GridFS.FindOneById(id);

            if (info == null)
            {
                throw new MongoException("文件不存在。");
            }

            DataBase.GridFS.Download(saveFile, info);
        }
コード例 #7
0
        private void ExportSelectedTor_Click(object sender, RoutedEventArgs e)
        {
            List <Dictionary <object, object> > items = new List <Dictionary <object, object> >();

            for (int i = 0; i < listBox.Items.Count; i++)
            {
                ListBoxItem lbt = (listBox.Items[i] as ListBoxItem);
                Dictionary <object, object> search = new Dictionary <object, object>();
                Dictionary <object, object> likes  = new Dictionary <object, object>();
                likes.Add("$regex", lbt.Tag);
                search.Add("file_name", likes);
                search.Add("content", lbt.Content.ToString());
                items.Add(search);
            }
            if (items.Count == 0)
            {
                return;
            }
            FolderBrowserDialog tor_bor = new FolderBrowserDialog();

            tor_bor.Description = "Please select where to save all torrents files";
            if (tor_bor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (Directory.Exists(tor_bor.SelectedPath))
                {
                    progressbar.Value = 0;
                    long   count = 0;
                    Thread th    = new Thread(new ThreadStart(delegate
                    {
                        items.ForEach(item =>
                        {
                            string Filepath = string.Join("", item["content"].ToString().Split());
                            Regex rg        = new Regex("[/*:?\"<>|\\\\s]");
                            Filepath        = rg.Replace(Filepath, "");
                            item.Remove("content");
                            MongoGridFSFileInfo mof = moop.GetFileByInfo("torrents", item);
                            using (FileStream fs = new FileStream(tor_bor.SelectedPath + "\\" + Filepath + ".torrent", FileMode.OpenOrCreate))
                            {
                                byte[] buf = new byte[mof.OpenRead().Length];
                                mof.OpenRead().Read(buf, 0, buf.Length);
                                fs.Write(buf, 0, buf.Length);
                                fs.Flush();
                            }
                            double val = Math.Round((count + 1) * 100.0 / items.Count, 1);
                            this.Dispatcher.Invoke(por, new object[] { val });
                            count++;
                        });
                        System.Windows.MessageBox.Show("Job Done", "Message");
                        this.Dispatcher.Invoke(por, new object[] { 0 });
                    }));
                    th.Start();
                }
            }
        }
コード例 #8
0
        public GridFsBlobDescriptor(BlobId blobId, MongoGridFSFileInfo mongoGridFsFileInfo)
        {
            if (mongoGridFsFileInfo == null)
            {
                throw new ArgumentNullException("mongoGridFsFileInfo");
            }
            _mongoGridFsFileInfo = mongoGridFsFileInfo;
            BlobId = blobId;

            FileNameWithExtension = new FileNameWithExtension(_mongoGridFsFileInfo.Name);
        }
コード例 #9
0
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog opnfd = new OpenFileDialog();

            opnfd.Filter      = "Image Files (*.jpg;*.jpeg;.*.gif;)|*.jpg;*.jpeg;.*.gif";
            opnfd.Multiselect = true;
            var connectionString = "mongodb://localhost/?safe=true";
            var server           = MongoServer.Create(connectionString);
            var db = server.GetDatabase("CookingBook");

            if (opnfd.ShowDialog() != DialogResult.Cancel)
            {
                sFileName = opnfd.FileName;

                if (File.Exists(sFileName))
                {
                    using (FileStream fs = File.OpenRead(sFileName))
                    {
                        // Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");

                        // Add some information to the file.
                        // fs.Write(info, 0, info.Length);
                        pictureBox1.Image = new Bitmap(fs.Name);

                        pictureBox1.Height = 150;
                        pictureBox1.Width  = 150;
                        UploadedFile       = db.GridFS.Upload(fs, sFileName);
                        fileId             = UploadedFile.Id;
                        fs.Close();
                    }
                }
            }

            /*
             *
             */

            /*using (FileStream fs = File.Open(sFileName, FileMode.Open, FileAccess.Read, FileShare.None))
             * {
             * try
             *  {
             *      var gridFsInfo = db.GridFS.Upload(fs, sFileName);
             *      var fileId = gridFsInfo.Id;
             *  }
             *
             *  catch (Exception ex)
             *  {
             *      Console.Write("Opening the file twice is disallowed.");
             *      Console.WriteLine(", as expected: {0}", ex.ToString());
             *  }
             * }
             */
        }
コード例 #10
0
        public MongoGridFSFileInfo GetFileByInfo(string set_name, Dictionary <object, object> search)
        {
            MongoGridFSSettings mgfs = new MongoGridFSSettings();

            mgfs.Root           = set_name;
            mgfs.ReadPreference = ReadPreference.Primary;
            mgfs.VerifyMD5      = true;
            mgfs.UpdateMD5      = true;
            MongoGridFSFileInfo file_info = mdbs.GetGridFS(mgfs).FindOne(Query.Create(new BsonDocument(search)));

            return(file_info);
        }
コード例 #11
0
ファイル: MongoDBHelper.cs プロジェクト: 1244952898/MQ_NEW
        public static void SetFileByName(string dbName, string filepath, string filename)
        {
            if (!File.Exists(filepath))
            {
                return;
            }
            MongoDatabase db = ServerInstance().GetDatabase(dbName);

            if (db.GridFS.Exists(filename.ToUpper()))
            {
                db.GridFS.Delete(filename.ToUpper());
            }
            MongoGridFSFileInfo fileInfo = db.GridFS.Upload(filepath, filename.ToUpper());
        }
コード例 #12
0
        public bool DeleteFileByID(ObjectId id)
        {
            try
            {
                MongoGridFSFileInfo file = _db.GridFS.FindOneById(id);
                if (file.Exists)
                {
                    file.Delete();
                }
            }
            catch { return(false); }

            return(true);
        }
コード例 #13
0
        /// <summary>
        /// 读取报表结果
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="rootName"></param>
        /// <returns></returns>
        public string ReadFileFromMongoDb(string filename, string rootName)
        {
            string              tablestr;
            MongoGridFS         fs     = GetGridFs(Dbname, rootName);
            MongoGridFSFileInfo gfInfo = new MongoGridFSFileInfo(fs, filename);

            using (MongoGridFSStream gfs = gfInfo.OpenRead())
            {
                using (TextReader reader = new StreamReader(gfs, Encoding.UTF8))
                {
                    tablestr = reader.ReadToEnd();
                }
            }
            return(tablestr);
        }
コード例 #14
0
        public byte[] GetFileByID(ObjectId id)
        {
            MongoGridFSFileInfo file = _db.GridFS.FindOneById(id);

            if (file.Exists)
            {
                using (var stream = file.OpenRead())
                {
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    return(buffer);
                }
            }

            return(null);
        }
コード例 #15
0
        /// <summary>
        /// 通过ObjectId下载文件
        /// </summary>
        /// <param name="id">ObjectId</param>
        /// <returns>返回流</returns>
        /// <exception cref="NotImplementedException">未实现异常</exception>
        public Stream DownLoad(ObjectId id)
        {
            MongoGridFSFileInfo info = DataBase.GridFS.FindOneById(id);

            if (info == null)
            {
                throw new MongoException("文件不存在。");
            }

            var stream = new MemoryStream();

            DataBase.GridFS.Download(stream, info);

            stream.Position = 0;
            return(stream);
        }
コード例 #16
0
        private void Load()
        {
            if (_fileInfo == null)             // True when Attachment is loaded from serialised Attachment property.
            {
                _fileInfo = GetGridFS().FindOneById(ID);
            }
            if (_fileInfo == null)
            {
                return;
            }

            _contentType = _fileInfo.ContentType;
            _fileName    = _fileInfo.Name;
            _metadata    = _fileInfo.Metadata;

            IsLoaded = true;
        }
コード例 #17
0
        public void CopyFile(string fromVirtualPath, string destinationVirtualPath)
        {
            MongoGridFS mongoGridFs = GetGridFS();

            string fixedDestinationPath = FixPath(destinationVirtualPath);

            mongoGridFs.CopyTo(FixPath(fromVirtualPath), fixedDestinationPath);

            MongoGridFSFileInfo fileInfo = mongoGridFs.FindOne(fixedDestinationPath);

            mongoGridFs.SetMetadata(fileInfo, CreateMetadata(fixedDestinationPath, false));

            if (FileCopied != null)
            {
                FileCopied.Invoke(this, new FileEventArgs(destinationVirtualPath, fromVirtualPath));
            }
        }
コード例 #18
0
        private FileData GetFileData(MongoGridFSFileInfo fileInfo)
        {
            DateTime modifiedDateTime = fileInfo.UploadDate;

            if (fileInfo.Metadata.Contains("modified_date"))
            {
                modifiedDateTime = (fileInfo.Metadata["modified_date"] as BsonDateTime).ToUniversalTime();
            }

            return(new FileData
            {
                Created = fileInfo.UploadDate,
                Updated = modifiedDateTime,
                Name = GetName(fileInfo.Name),
                VirtualPath = fileInfo.Name,
                Length = fileInfo.Length
            });
        }
コード例 #19
0
        public GANFile DownloadFile(string fileId)
        {
            var ganFile = GANFile.AsQueryable().FirstOrDefault(q => q.FileId == fileId);

            byte[] doc = null;

            // Read the file document from GridFS into a memory stream so we can convert it to a byte array.
            using (MemoryStream output = new MemoryStream())
            {
                MongoGridFSFileInfo info = Files.GridFs.FindOneById(new BsonObjectId(new ObjectId(ganFile.FileId)));
                info.GridFS.Download(output, info);
                doc = output.ToArray();
            }

            // Assign the file property of our attachment and return the resulting instance.
            ganFile.File = doc;
            return(ganFile);
        }
コード例 #20
0
ファイル: MongoDBHelper.cs プロジェクト: 1244952898/MQ_NEW
        public static void SetFileByName(string dbName, Stream filestream, string filename)
        {
            if (filestream == null)
            {
                return;
            }

            MongoDatabase db = ServerInstance().GetDatabase(dbName);

            if (db.GridFS.Exists(filename.ToUpper()))
            {
                db.GridFS.Delete(filename.ToUpper());
            }
            filestream.Seek(0, SeekOrigin.Begin);//将当前流的位置设置为初始位置。很重要,很重要,很重要!!!( add on 2016/5/4 by wangqi)
            MongoGridFSFileInfo fileInfo = db.GridFS.Upload(filestream, filename.ToUpper(), new MongoGridFSCreateOptions()
            {
                ContentType = GetContentType(filename)
            });
        }
コード例 #21
0
ファイル: AttachmentService.cs プロジェクト: Myslik/opencat
        private static Attachment FromFileInfo(MongoGridFSFileInfo info)
        {
            var attachment = new Attachment
            {
                id           = info.Id.ToString(),
                name         = info.Name,
                size         = info.Length,
                md5          = info.MD5,
                uploaded_at  = info.UploadDate,
                content_type = info.ContentType,
                info         = info
            };

            if (info.Metadata.Contains("job_id"))
            {
                attachment.job_id = info.Metadata["job_id"].ToString();
            }
            return(attachment);
        }
コード例 #22
0
        private void ExportAllViews_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog tor_bor = new FolderBrowserDialog();

            tor_bor.Description = "Please select where to save all preview files";
            if (tor_bor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (Directory.Exists(tor_bor.SelectedPath))
                {
                    progressbar.Value = 0;
                    long   count = 0;
                    Thread th    = new Thread(new ThreadStart(delegate
                    {
                        moop.FindByKVPair("resources", moop.FilterBuilder(null)).ForEach(item =>
                        {
                            if (item.GetValue("preview").ToString() == "")
                            {
                                return;
                            }
                            MongoGridFSFileInfo mof = moop.GetFileById("previews", item.GetValue("preview").ToString());
                            string Filepath         = string.Join("", item.GetValue("name").ToString().Split());
                            Regex rg = new Regex("[/*:?\"<>|\\\\s]");
                            Filepath = rg.Replace(Filepath, "");
                            using (FileStream fs = new FileStream(tor_bor.SelectedPath + "\\" + Filepath + ".jpg", FileMode.OpenOrCreate))
                            {
                                byte[] buf = new byte[mof.OpenRead().Length];
                                mof.OpenRead().Read(buf, 0, buf.Length);
                                fs.Write(buf, 0, buf.Length);
                                fs.Flush();
                            }
                            double val = Math.Round((count + 1) * 100.0 / total_count, 1);
                            this.Dispatcher.Invoke(por, new object[] { val });
                            count++;
                        });
                        System.Windows.MessageBox.Show("Done");
                        this.Dispatcher.Invoke(por, new object[] { 0 });
                    }));
                    th.Start();
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// 下载指定标识的文件
        /// </summary>
        /// <param name="id">ObjectId</param>
        /// <param name="saveFile">保存文件路径</param>
        /// <returns></returns>
        public void DownLoad(ObjectId id, string saveFile)
        {
            if (id == ObjectId.Empty)
            {
                throw new ArgumentNullException("id");
            }

            if (string.IsNullOrEmpty(saveFile))
            {
                throw new ArgumentNullException("saveFile");
            }

            MongoGridFSFileInfo info = DataBase.GridFS.FindOneById(id);

            if (info == null)
            {
                throw new MongoException("文件不存在。");
            }

            DataBase.GridFS.Download(saveFile, info);
        }
コード例 #24
0
ファイル: TestGridFS.cs プロジェクト: chaiwat-kh/Lab-MongoDB
        public void TestReadGridFS2Array()
        {
            var server = MongoServer.Create("mongodb://localhost:27017");
            var db     = server.GetDatabase("dcm");

            var where = Query.EQ("md5", "cac1807172774be5d48937cee90c9e84");

            MongoGridFS         fs       = db.GridFS;
            MongoGridFSFileInfo fileInfo = fs.FindOne(where);
            MongoGridFSStream   readerFS = fileInfo.Open(System.IO.FileMode.Open);
            List <byte>         readByte = new List <byte>();
            int bufferSize = 4048;

            byte[] buffer    = new byte[bufferSize];
            int    readCount = readerFS.Read(buffer, 0, bufferSize);

            while (readCount > 0)
            {
                readByte.AddRange(buffer.Take(readCount).ToArray());
                readCount = readerFS.Read(buffer, 0, bufferSize);
            }
        }
コード例 #25
0
        public Stream OpenFile(string virtualPath, bool readOnly = false)
        {
            string fixedPath = FixPath(virtualPath);

            if (!FileExists(fixedPath) && !readOnly)
            {
                InternalWriteFile(fixedPath, new MemoryStream(new byte[0]));
            }

            MongoGridFS gridFs = GetGridFS();

            if (readOnly)
            {
                return(gridFs.OpenRead(fixedPath));
            }

            MongoGridFSFileInfo fileInfo = gridFs.FindOne(fixedPath);

            gridFs.SetMetadata(fileInfo, CreateMetadata(fixedPath, false));

            return(gridFs.OpenWrite(fixedPath));
        }
コード例 #26
0
        private DirectoryData GetDirectoryData(MongoGridFSFileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                return(null);
            }

            DateTime modifiedDateTime = fileInfo.UploadDate;

            if (fileInfo.Metadata.Contains("modified_date"))
            {
                modifiedDateTime = (fileInfo.Metadata["modified_date"] as BsonDateTime).ToUniversalTime();
            }

            return(new DirectoryData
            {
                Created = fileInfo.UploadDate,
                Updated = modifiedDateTime,
                Name = GetName(fileInfo.Name),
                VirtualPath = fileInfo.Name,
            });
        }
コード例 #27
0
        /// <summary>
        /// 下载指定条件的文件
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="saveFile">保存文件路径</param>
        public void DownLoad(IDictionary <string, object> condition, string saveFile)
        {
            if (string.IsNullOrEmpty(saveFile))
            {
                throw new ArgumentNullException("saveFile");
            }

            if (condition == null || condition.Count == 0)
            {
                throw new InstrumentationException("条件condition不能为null或键数据为0。");
            }

            var query = new QueryDocument(DictionaryWarp(condition));
            MongoGridFSFileInfo info = DataBase.GridFS.FindOne(query);

            if (info == null)
            {
                throw new MongoException("文件不存在。");
            }

            DataBase.GridFS.Download(saveFile, info);
        }
コード例 #28
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="condition">下载字典条件</param>
        /// <returns>返回下载流数据</returns>
        public Stream DownLoad(IDictionary <string, object> condition)
        {
            if (condition == null || condition.Count == 0)
            {
                throw new InstrumentationException("条件condition不能为null或键数据为0。");
            }

            var query = new QueryDocument(DictionaryWarp(condition));
            MongoGridFSFileInfo info = DataBase.GridFS.FindOne(query);

            if (info == null)
            {
                throw new MongoException("文件不存在。");
            }

            var stream = new MemoryStream();

            DataBase.GridFS.Download(stream, info);

            stream.Position = 0;
            return(stream);
        }
コード例 #29
0
ファイル: MongoInit.cs プロジェクト: ststeiger/MongoUpload
        static void Test2()
        {
            MongoServer ms      = MongoServer.Create();
            string      _dbName = "docs";

            MongoDatabase md = ms.GetDatabase(_dbName);

            if (!md.CollectionExists(_dbName))
            {
                md.CreateCollection(_dbName);
            } // End if (!md.CollectionExists(_dbName))

            MongoCollection <Doc> _documents = md.GetCollection <Doc>(_dbName);

            _documents.RemoveAll();
            //add file to GridFS

            MongoGridFS         gfs  = new MongoGridFS(md);
            MongoGridFSFileInfo gfsi = gfs.Upload(@"c:\mongodb.rtf");

            _documents.Insert(new Doc()
            {
                DocId   = gfsi.Id.AsObjectId,
                DocName = @"c:\foo.rtf"
            }
                              );

            foreach (Doc item in _documents.FindAll())
            {
                ObjectId            _documentid = new ObjectId(item.DocId.ToString());
                MongoGridFSFileInfo _fileInfo   = md.GridFS.FindOne(Query.EQ("_id", _documentid));
                gfs.Download(item.DocName, _fileInfo);
                System.Console.WriteLine("Downloaded {0}", item.DocName);
                System.Console.WriteLine("DocName {0} dowloaded", item.DocName);
            } // Next item

            //System.Console.ReadKey();
        } // End Sub Test2
コード例 #30
0
        public HttpResponseMessage GetFileByObjectId(string objectId)
        {
            MongoClient   client   = new MongoClient("mongodb://localhost");
            MongoDatabase database = client.GetServer().GetDatabase("test");
            Form          form     = database.GetCollection("forms").AsQueryable <Form>()
                                     .Where(o => o.FileId == objectId)
                                     .FirstOrDefault();

            ObjectId            fileId = new ObjectId(form.FileId);
            MongoGridFSFileInfo file   = database.GridFS.FindOne(Query.EQ("_id", fileId));

            using (var stream = file.OpenRead())
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);

                HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                httpResponseMessage.Content = new ByteArrayContent(bytes);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                httpResponseMessage.StatusCode = HttpStatusCode.OK;
                return(httpResponseMessage);
            }
        }