Exemple #1
0
        public int ReadFile(string filename, byte[] buffer, ref uint readBytes, long offset, DokanFileInfo info)
        {
            Trace.TraceInformation("ReadFile: {0}", filename);

            var file = _gridFs.FindOne(GetPath(filename));

            if (file == null)
            {
                Trace.TraceWarning("File {0} was not found", filename);
                return(-1);
            }

            try
            {
                using (var fs = file.OpenRead())
                {
                    fs.Seek(offset, SeekOrigin.Begin);
                    readBytes = (uint)fs.Read(buffer, 0, buffer.Length);
                    return(0);
                }
            }catch (Exception e)
            {
                Trace.TraceError(e.Message + Environment.NewLine + e.Message);
                return(-1);
            }
        }
Exemple #2
0
        public void TestFindOneByName()
        {
            _gridFS.Delete(Query.Null);
            Assert.IsFalse(_gridFS.Exists("HelloWorld.txt"));

            var fileInfo  = UploadHelloWorld();
            var foundInfo = _gridFS.FindOne("HelloWorld.txt");

            Assert.AreEqual(fileInfo, foundInfo);
        }
Exemple #3
0
        public void FindOneByNameTest()
        {
            gridFS.Delete(Query.Null);
            Assert.IsFalse(gridFS.Exists(UploadFileName));

            var fileInfo  = UploadHelloWord();
            var foundInfo = gridFS.FindOne(UploadFileName);

            Assert.AreEqual(fileInfo, foundInfo);
        }
Exemple #4
0
 /// <summary>
 /// 获取文件
 /// </summary>
 /// <param name="fileName">文件名</param>
 /// <param name="fileDBName">文件数据库名</param>
 /// <returns>Stream</returns>
 public virtual byte[] GetFileAsStream(string fileName, string fileDBName)
 {
     try
     {
         if (string.IsNullOrEmpty(fileName))
         {
             throw new KnownException("名称为空,无法获取!");
         }
         MongoGridFSSettings fsSetting = new MongoGridFSSettings()
         {
             Root = fileDBName
         };
         MongoGridFS fs     = new MongoGridFS(_server, _database.Name, fsSetting);
         var         gfInfo = fs.FindOne(fileName);
         using (var stream = gfInfo.OpenRead())
         {
             var bytes = new byte[stream.Length];
             stream.Read(bytes, 0, (int)stream.Length);
             return(bytes);
         }
     }
     catch (Exception)
     {
         return(new byte[0]);
     }
 }
        public override Task <Stream> OpenAsync(string virtualPath, NameValueCollection queryString)
        {
            var _filename = virtualPath.Substring(VirtualFilesystemPrefix.Length);

            //First try to get it by id, next by filename
            if (_filename.StartsWith("id/", StringComparison.OrdinalIgnoreCase))
            {
                //Strip the extension and id/ prefix
                var sid = PathUtils.RemoveFullExtension(_filename.Substring(3));

                ObjectId id;

                if (ObjectId.TryParse(sid, out id))
                {
                    var file = _grid.FindOne(MongoDB.Driver.Builders.Query.EQ("_id", id));

                    if (file == null)
                    {
                        throw new FileNotFoundException("Failed to locate blob " + sid + " on GridFS.");
                    }

                    return(Task.FromResult <Stream>(file.OpenRead()));
                }
            }

            return(Task.FromResult <Stream>(_grid.OpenRead(_filename)));
        }
Exemple #6
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)));
        }
        private byte[] ReadFile(string fileName)
        {
            var found = m_grid.FindOne(Query.Matches("filename", new BsonRegularExpression(new Regex("^" + Regex.Escape(fileName) + "$", RegexOptions.IgnoreCase))));

            byte[] bytes;
            using (var g = found.OpenRead())
            {
                bytes = new byte[g.Length];
                g.Read(bytes, 0, bytes.Length);
            }

            return(bytes);
        }
        public Stream DownloadFile(FileModel file)
        {
            var result = _gridFS.FindOne(Query.And(
                                             Query.EQ("PatientID", file.PatientID), Query.EQ("Filename", file.Filename)
                                             ));


            if (result == null)
            {
                throw new Exception("Could not find file by that ID.");
            }

            return(result.OpenRead());
        }
Exemple #9
0
        /// <summary>
        /// find file by its filepath
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public IStorageFile Find(string filepath)
        {
            if (string.IsNullOrWhiteSpace(filepath))
            {
                throw new ArgumentException("filepath cannot be null or empty");
            }

            //all filepaths are lowercase and all starts with folder separator
            filepath = filepath.ToLowerInvariant();
            if (!filepath.StartsWith(FOLDER_SEPARATOR))
            {
                filepath = FOLDER_SEPARATOR + filepath;
            }

            var file = gfs.FindOne(filepath);

            if (file == null)
            {
                return(null);
            }

            return(new MongoStorageFile(file));
        }
Exemple #10
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));
            }
        }
Exemple #11
0
        public static FileInformation FindFileOrDir(this MongoGridFS that, string filename)
        {
            var file = that.FindOne(filename);

            if (file != null)
            {
                return(file.GetFileInformation());
            }

            // okay, we should search for a directory
            var childCount = that.Files.Count(Query.Matches("filename", String.Format(@"/^{0}\\.+/", Regex.Escape(filename.TrimEnd('\\')))));

            if (childCount > 0)
            {
                return(NewDirectory(Path.GetFileName(filename)));
            }
            return(null);
        }
Exemple #12
0
        /// <summary>
        /// 获取元数据信息
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public MetaInfo GetMeta(string remoteFile)
        {
            _logger.DebugFormat("GetMeta By Id{0}.", remoteFile);

            MongoGridFS fs = new MongoGridFS(_context.DataBase);

            if (!fs.Exists(remoteFile))
            {
                return(null);
            }

            var info = fs.FindOne(remoteFile);

            return(new MetaInfo
            {
                fileName = remoteFile,
                MD5 = info.MD5,
                MimeType = info.ContentType,
            });
        }
Exemple #13
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));
        }
Exemple #14
0
        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);
            }
        }
Exemple #15
0
        public void TestCreateZeroLengthFile()
        {
            gridFS.Files.RemoveAll();
            gridFS.Chunks.RemoveAll();
            gridFS.Chunks.ResetIndexCache();

            var fileInfo = gridFS.FindOne("test");

            Assert.IsNull(fileInfo);

            using (var stream = gridFS.Create("test"))
            {
                Assert.IsTrue(stream.CanRead);
                Assert.IsTrue(stream.CanSeek);
                Assert.IsFalse(stream.CanTimeout);
                Assert.IsTrue(stream.CanWrite);
                Assert.AreEqual(0, stream.Length);
                Assert.AreEqual(0, stream.Position);

                fileInfo = gridFS.FindOne("test");
                Assert.IsTrue(fileInfo.Exists);
                Assert.IsNull(fileInfo.Aliases);
                Assert.AreEqual("test", fileInfo.Name);
                Assert.AreEqual(gridFS.Settings.ChunkSize, fileInfo.ChunkSize);
                Assert.IsNull(fileInfo.ContentType);
                Assert.AreEqual(0, fileInfo.Length);
                Assert.IsNull(fileInfo.MD5);
                Assert.IsNull(fileInfo.Metadata);
            }

            fileInfo = gridFS.FindOne("test");
            Assert.IsTrue(fileInfo.Exists);
            Assert.AreEqual(0, fileInfo.Length);
            Assert.IsNotNull(fileInfo.MD5);
        }