Ejemplo n.º 1
0
        public void AppendTextTest()
        {
            Assert.IsFalse(gridFS.Exists("HelloWorld.txt"));
            using (var writer = gridFS.AppendText("HelloWorld.txt")) {
                Assert.IsFalse(writer.BaseStream.CanRead);
                Assert.IsTrue(writer.BaseStream.CanSeek);
                Assert.IsTrue(writer.BaseStream.CanWrite);
                writer.Write("동해물과");
            }

            Assert.IsTrue(gridFS.Exists("HelloWorld.txt"));
            using (var writer = gridFS.AppendText("HelloWorld.txt")) {
                writer.Write(" 백두산이");
            }
            var memoryStream = new MemoryStream();

            gridFS.Download(memoryStream, "HelloWorld.txt");
            var bytes = memoryStream.ToArray();

            // 2-byte 문자열임을 나타내는 헤더값
            StringTool.IsMultiByteString(bytes).Should().Be.True();

            //Assert.AreEqual(0xEF, bytes[0]); // the BOM
            //Assert.AreEqual(0xBB, bytes[1]);
            //Assert.AreEqual(0xBF, bytes[2]);

            // Header 값을 빼고, 한다.
            // var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
            var text = memoryStream.ToText(Encoding.UTF8);

            Assert.AreEqual("동해물과 백두산이", text);
        }
Ejemplo n.º 2
0
        public void TestAppendText()
        {
            _gridFS.Delete(Query.Null);
            Assert.IsFalse(_gridFS.Exists("HelloWorld.txt"));
            using (var writer = _gridFS.AppendText("HelloWorld.txt"))
            {
                Assert.IsFalse(writer.BaseStream.CanRead);
                Assert.IsTrue(writer.BaseStream.CanSeek);
                Assert.IsTrue(writer.BaseStream.CanWrite);
                writer.Write("Hello");
            }
            Assert.IsTrue(_gridFS.Exists("HelloWorld.txt"));
            using (var writer = _gridFS.AppendText("HelloWorld.txt"))
            {
                writer.Write(" World");
            }
            var memoryStream = new MemoryStream();

            _gridFS.Download(memoryStream, "HelloWorld.txt");
            var bytes = memoryStream.ToArray();

            Assert.AreEqual(0xEF, bytes[0]); // the BOM
            Assert.AreEqual(0xBB, bytes[1]);
            Assert.AreEqual(0xBF, bytes[2]);
            var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);

            Assert.AreEqual("Hello World", text);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void DownloadFile(String strLocalFileName, String strRemoteFileName)
        {
            MongoDatabase mongoDB = SystemManager.GetCurrentDataBase();
            MongoGridFS   gfs     = mongoDB.GetGridFS(new MongoGridFSSettings());

            gfs.Download(strLocalFileName, strRemoteFileName);
        }
Ejemplo n.º 4
0
        ///在使用GirdFileSystem的时候,请注意:
        ///1.Windows 系统的文件名不区分大小写,不过,filename一定是区分大小写的,如果大小写不匹配的话,会发生无法找到文件的问题
        ///2.Download的时候,不能使用SlaveOk选项!

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void OpenFile(String strRemoteFileName)
        {
            MongoDatabase mongoDB = SystemManager.GetCurrentDataBase();
            MongoGridFS   gfs     = mongoDB.GetGridFS(new MongoGridFSSettings());

            String[] strLocalFileName = strRemoteFileName.Split(System.IO.Path.DirectorySeparatorChar);

            try
            {
                if (!Directory.Exists(TempFileFolder))
                {
                    Directory.CreateDirectory(TempFileFolder);
                }
                String LocalFileName = TempFileFolder + System.IO.Path.DirectorySeparatorChar + strLocalFileName[strLocalFileName.Length - 1];
                gfs.Download(LocalFileName, strRemoteFileName);
                System.Diagnostics.Process.Start(LocalFileName);
            }
            catch (System.ComponentModel.Win32Exception)
            {
                MyMessageBox.ShowEasyMessage("Error", "No Program can open this file");
            }
            catch (Exception ex)
            {
                SystemManager.ExceptionDeal(ex, "Error", "Exception happend when open file");
            }
        }
        static void Main(string[] args)
        {
            MongoServer   ms      = MongoServer.Create();
            string        _dbName = "docs";
            MongoDatabase md      = ms.GetDatabase(_dbName);

            if (!md.CollectionExists(_dbName))
            {
                md.CreateCollection(_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);
                Console.WriteLine("Downloaded {0}", item.DocName);
                Console.WriteLine("DocName {0} dowloaded", item.DocName);
            }
            Console.ReadKey();
        }
Ejemplo n.º 6
0
        public Dictionary <string, string> BuscarArquivo(string id, ref MemoryStream retorno)
        {
            var fileInfo  = database.GridFS.FindOne(Query.EQ("_id", new BsonObjectId(new ObjectId(id))));
            var mySetting = new MongoGridFSSettings();
            var gfs       = new MongoGridFS(server, database.Name, mySetting);

            gfs.Download(retorno, fileInfo);
            return(new Dictionary <string, string> {
                { fileInfo.ContentType, fileInfo.Name }
            });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 下载文档到本地
        /// </summary>
        /// <param name="localfile"></param>
        /// <param name="remoteFile"></param>
        public void Copy(string localfile, string remoteFile)
        {
            _logger.DebugFormat("Copy {0} to {1}.", localfile, remoteFile);

            try
            {
                MongoGridFS fs = new MongoGridFS(_context.DataBase);
                fs.Download(localfile, remoteFile);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
Ejemplo n.º 8
0
        private static void Main()
        {
            var exit = false;

            _mongoClient = new MongoClient("mongodb://localhost");
            _db          = new MongoGridFS(_mongoClient.GetServer(), "Default",
                                           new MongoGridFSSettings());
            while (!exit)
            {
                Console.Write(GetPrepend());
                var command = Console.ReadLine();
                Debug.Assert(command != null, "command != null");
                if (command.Length == 0)
                {
                    continue;
                }
                //What the f**k?
                //Handles quotation marks in incoming commands
                var result = command.Split('"')
                             .Select((element, index) => index % 2 == 0
                        ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        : new[] { element })
                             .SelectMany(element => element).ToList();
                switch (result[0].ToLower())
                {
                case "exit":
                    exit = true;
                    break;

                case "cd":
                    if (result.Count == 2)
                    {
                        if (result[1] == "..")
                        {
                            var sarray = _currentdirectory.Split('/').Where(x => x != "").ToArray();
                            var str    = "/";
                            for (var i = 0; i < sarray.Length - 1; i++)
                            {
                                str += sarray[i] + "/";
                            }
                            _currentdirectory = str;
                        }
                        else
                        {
                            _currentdirectory += result[1] + "/";
                        }
                    }
                    else
                    {
                        Console.WriteLine("  Usage: cd <dir>");
                    }
                    break;

                case "server":
                    _mongoClient = new MongoClient("mongodb://" + result[1]);
                    _db          = new MongoGridFS(_mongoClient.GetServer(), "Default",
                                                   new MongoGridFSSettings());
                    break;

                case "db":
                    _db = new MongoGridFS(_mongoClient.GetServer(), result[1],
                                          new MongoGridFSSettings());
                    break;

                case "ls":
                    if (_db != null)
                    {
                        var query = from file in _db.FindAll()
                                    where file.Name.StartsWith(_currentdirectory)
                                    select file;
                        foreach (var file in query)
                        {
                            Console.WriteLine("  " + file.Name);
                        }
                    }
                    break;

                case "put":
                    if (result.Count == 2)
                    {
                        var file = new FileInfo(result[1]);
                        if (!file.Exists)
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Uploading " + file.Name + "...");
                        Debug.Assert(_db != null, "_db != null");
                        _db.Upload(file.FullName, _currentdirectory + file.Name);
                        Console.WriteLine("Done!");
                    }
                    else if (result.Count == 3)
                    {
                        var file = new FileInfo(result[1]);
                        if (!file.Exists)
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Uploading " + file.Name + "...");
                        Debug.Assert(_db != null, "_db != null");
                        _db.Upload(file.FullName, result[2]);
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        Console.WriteLine("  Usage: put <src> [dest]");
                    }
                    break;

                case "get":
                    if (result.Count == 2)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Downloading " + result[1] + "...");
                        _db.Download(result[1], result[1]);
                        Console.WriteLine("Done!");
                    }
                    else if (result.Count == 3)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Downloading " + result[1] + "...");
                        _db.Download(result[2], result[1]);
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        Console.WriteLine("  Usage: get <src> [dest]");
                    }
                    break;

                case "del":
                    if (result.Count == 2)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        _db.Delete(result[1]);
                    }
                    else
                    {
                        Console.WriteLine("  Usage: del <filename>");
                    }
                    break;

                default:
                    Console.WriteLine("  Invalid Command");
                    break;
                }
            }
        }