Open() public static method

public static Open ( String path, FileMode mode ) : FileStream
path String
mode FileMode
return FileStream
Esempio n. 1
0
        public async Task RoleSortTestAsync()
        {
            var samplePath = @"C:/Users/13xforever/Downloads/names.txt";
            var resultPath = Path.Combine(Path.GetDirectoryName(samplePath), "role_count.txt");

            var stats = new int[10];
            var names = await File.ReadAllLinesAsync(samplePath, Encoding.UTF8);

            await using var r = File.Open(resultPath, FileMode.Create, FileAccess.Write, FileShare.Read);
            await using var w = new StreamWriter(r, new UTF8Encoding(false));
            foreach (var line in names)
            {
                var user      = UserInfo.Parse(line);
                var roleCount = user.Roles?.Length ?? 0;
                stats[roleCount]++;
                w.Write(roleCount);
                await w.WriteAsync('\t').ConfigureAwait(false);

                await w.WriteLineAsync(user.DisplayName).ConfigureAwait(false);
            }

            for (var i = 0; i < stats.Length && stats[i] > 0; i++)
            {
                Console.WriteLine($"{i:#0} roles: {stats[i]} members");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates new instance of Song and maps all IDv info about it to the class.
        /// </summary>
        public static Song New(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(nameof(filePath));
            }

            var reader = File.Open(filePath, FileMode.Open);

            var streamFileAbstraction = new StreamFileAbstraction(filePath, reader, reader);

            var tagFile = TagLib.File.Create(streamFileAbstraction);

            reader.Close();

            return(new Song
            {
                Name = System.IO.Path.GetFileNameWithoutExtension(filePath),
                Path = filePath,
                Artist = tagFile.Tag.FirstAlbumArtist,
                Album = tagFile.Tag.Album,
                Title = tagFile.Tag.Title,
                Year = tagFile.Tag.Year,
                Lenght = tagFile.Length
            });
        }
Esempio n. 3
0
        private async Task ZipAllFilesToStream(
            Release release,
            Stream outputStream,
            CancellationToken?cancellationToken = null)
        {
            var releaseFiles = (await QueryReleaseFiles(release.Id).ToListAsync())
                               .OrderBy(rf => rf.File.ZipFileEntryName())
                               .ToList();

            var path       = Path.GetTempPath() + release.AllFilesZipFileName();
            var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            await using var multiWriteStream = new MultiWriteStream(outputStream, fileStream);

            await DoZipFilesToStream(releaseFiles, release, multiWriteStream, cancellationToken);

            await multiWriteStream.FlushAsync();

            // Now cache the All files zip into blob storage
            // so that we can quickly fetch it again.
            fileStream.Position = 0;

            await _blobStorageService.UploadStream(
                containerName : PublicReleaseFiles,
                path : release.AllFilesZipPath(),
                stream : fileStream,
                contentType : MediaTypeNames.Application.Zip
                );

            await fileStream.DisposeAsync();

            File.Delete(path);
        }
Esempio n. 4
0
        private void log(string refName, byte[] rec)
        {
            FileInfo log = logFor(refName);
            bool     write;

            if (isLogAllRefUpdates() && shouldAutoCreateLog(refName))
            {
                write = true;
            }
            else if (log.IsFile())
            {
                write = true;
            }
            else
            {
                write = false;
            }

            if (write)
            {
                DirectoryInfo dir = log.Directory;
                if (!dir.Mkdirs() && !dir.IsDirectory())
                {
                    throw new IOException("Cannot create directory " + dir);
                }

                using (var sw = File.Open(log.FullName, System.IO.FileMode.Append))
                    using (var @out = new BinaryWriter(sw))
                    {
                        @out.Write(rec);
                    }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Просмотр файла.
        /// </summary>
        public string view()
        {
            string str = string.Empty;

            if (SFile.Exists(fname) & fname.Length <= 260)//проверка на существование файла и корректность имени
            {
                try
                {
                    System.IO.FileStream stream1 = SFile.Open(fname, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite); //связываем наш поток с файлом
                    StreamReader         Reader  = new StreamReader(stream1);                                                                                 // создаем «потоковый читатель» и связываем его с файловым потоком
                    str = Reader.ReadToEnd();                                                                                                                 //считываем все данные с потока и выводим на экран
                    Reader.Close();                                                                                                                           //закрываем потоковый читатель
                    stream.Close();                                                                                                                           //закрываем поток
                }

                catch (Exception e)                                //обработка исключений для читателя
                {
                    LogForOperations("Просмотр файла", e.Message); //запись в лог ошибки (если есть)
                    throw e;
                }
            }
            else
            {
                LogForOperations("Просмотр файла", "файл не существует либо содержит в своем имени более 260 символов");//запись ошибки в лог, если не выполняется условие проверки
            }
            return(str);
        }
Esempio n. 6
0
        protected bool IsFileUsedbyAnotherProcess(string filename)
        {
            var info = new FileInfo(filename);

            if (!info.Exists)
            {
                return(false);
            }

            FileStream fs = null;

            try
            {
                fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
            }
            catch (IOException)
            {
                return(true);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            return(false);
        }
Esempio n. 7
0
        /// <summary>
        /// Смена кодировки.
        /// </summary>
        public void coding()
        {
            byte[] buffer                = new byte[4096];                                                                                            //буфер 1
            byte[] newBuffer             = new byte[4096];                                                                                            //буфер 2
            System.IO.FileStream stream1 = SFile.Open(fname, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite); //связываем наш поток с файлом
            while (stream1.Position < stream1.Length)                                                                                                 //пока позиция меньше длины
            {
                try
                {
                    int count = stream1.Read(buffer, 0, buffer.Length);//запись байтов в 1 буфер

                    for (int i = 0; i < count - 1; i++)
                    {
                        newBuffer = Encoding.ASCII.GetBytes(buffer[i] + " "); //меняем кодировку, записывая в буфер 2
                    }
                    stream1.Write(newBuffer, 0, newBuffer.Length);            //запись ф файловый поток
                    stream1.Flush();                                          //очищаем фуферы
                }
                catch (Exception ex)                                          //обработка исключений для смены кодировки
                {
                    LogForOperations("Смена кодировки файла", ex.Message);    //запись в лог ишибки (если есть)
                    throw ex;
                }
            }
        }
Esempio n. 8
0
                    static async Task SendEditImage(Message message)
                    {
                        try
                        {
                            await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

                            if (message == null || message.Type != MessageType.Text)
                            {
                                var file_info = await Bot.GetFileAsync(message.Photo.LastOrDefault().FileId);

                                string fileName = file_info.FileId + "." + file_info.FilePath.Split('.').Last();

                                using (var saveImageStream = File.Open(@"C:\ImageTelegram\" + fileName, FileMode.Create))
                                {
                                    await Bot.DownloadFileAsync(file_info.FilePath, saveImageStream);
                                }
                            }
                            else
                            {
                                await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : "Error! Send some image.");
                            }

                            await Bot.SendTextMessageAsync(
                                chatId : message.Chat.Id,
                                text : "Downloaded"
                                );
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error downloading: " + ex.Message);
                        }
                    }
Esempio n. 9
0
        private static void Add(ZipArchive archive, string folder, string fileName)
        {
            var sourceFilePath = Path.Combine(folder, fileName);

            if (!File.Exists(sourceFilePath))
            {
                return;
            }

            using (var stream = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var zipArchiveEntry = archive.CreateEntry(fileName);
                var dateTime        = File.GetLastWriteTime(sourceFilePath);
                if (dateTime.Year < 1980 || dateTime.Year > 2107)
                {
                    dateTime = new DateTime(1980, 1, 1, 0, 0, 0);
                }

                zipArchiveEntry.LastWriteTime = dateTime;
                using (var targetStream = zipArchiveEntry.Open())
                {
                    stream.CopyTo(targetStream);
                }
            }
        }
Esempio n. 10
0
 private void btn_FileExcel_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog openFileDialog = new OpenFileDialog()
     {
         Filter = "TestImportC#|*.xlsx"
     })
     {
         if (openFileDialog.ShowDialog() == DialogResult.OK)
         {
             txtBox_FileExcel.Text = openFileDialog.FileName;
             using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
             {
                 using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                 {
                     DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                     {
                         ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                         {
                             UseHeaderRow = true
                         }
                     });
                     tableCollection = result.Tables;
                     cbbox_import2.Items.Clear();
                     foreach (DataTable item in tableCollection)
                     {
                         cbbox_import2.Items.Add(item.TableName);
                     }
                 }
             }
         }
     }
 }
        public void Save()
        {
            FileStream streamFile = SystemIOFile.Open(FileName, FileMode.Create);

            XmlHistoricalRecordings.Serialize(streamFile, this);
            streamFile.Close();
        }
Esempio n. 12
0
        public static void Load(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                var usersId = context.Session.GetInt32("users_id");
                if (usersId == null)
                {
                    if (context.Request.Cookies.ContainsKey("users_id"))
                    {
                        usersId       = int.Parse(context.Request.Cookies["users_id"]);
                        var usersName = context.Request.Cookies["users_name"];
                        context.Session.SetInt32("users_id", (int)usersId);
                        context.Session.SetString("users_name", usersName);
                    }
                }
                var file          = context.Request.Form.Files.GetFile("file");
                var fileName      = Path.GetFileNameWithoutExtension(file.FileName);
                var fileExtension = Path.GetExtension(file.FileName);

                var newFile = new Models.File((int)usersId, fileName, fileExtension);
                var fileDao = new FileDao();
                fileDao.Save(newFile);

                await using (var fileStream = File.Open($"wwwroot\\files\\{file.FileName}", FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            });
        }
        List <LogglyEvent> GetListOfEvents(string currentFile, ref long nextLineBeginsAtOffset, ref int count)
        {
            var events = new List <LogglyEvent>();

            using (var current = IOFile.Open(currentFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                current.Position = nextLineBeginsAtOffset;

                string nextLine;
                while (count < _batchPostingLimit &&
                       TryReadLine(current, ref nextLineBeginsAtOffset, out nextLine))
                {
                    // Count is the indicator that work was done, so advances even in the (rare) case an
                    // oversized event is dropped.
                    ++count;

                    if (_eventBodyLimitBytes.HasValue && Encoding.UTF8.GetByteCount(nextLine) > _eventBodyLimitBytes.Value)
                    {
                        SelfLog.WriteLine(
                            "Event JSON representation exceeds the byte size limit of {0} and will be dropped; data: {1}",
                            _eventBodyLimitBytes, nextLine);
                    }
                    else
                    {
                        events.Add(DeserializeEvent(nextLine));
                    }
                }
            }

            return(events);
        }
        public MessagingServer(string editorExecutablePath, string projectMetadataDir, ILogger logger)
        {
            this.logger = logger;

            MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName);

            // Make sure the directory exists
            Directory.CreateDirectory(projectMetadataDir);

            // The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing...
            const FileShare metaFileShare = FileShare.ReadWrite;

            metaFile = File.Open(MetaFilePath, FileMode.Create, FileAccess.Write, metaFileShare);

            listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port: 0));
            listener.Start();

            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;

            using (var metaFileWriter = new StreamWriter(metaFile, Encoding.UTF8))
            {
                metaFileWriter.WriteLine(port);
                metaFileWriter.WriteLine(editorExecutablePath);
            }
        }
        private void NewAdd(string fileName)
        {
            //新增檔案

            //讀取檔案資料
            FileStream   loadFile   = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            BinaryReader filereader = new BinaryReader(loadFile);

            //存入陣列中
            //byte[] filecontent = filereader.ReadBytes(System.Convert.ToInt32(loadFile.Length));
            filereader.Close();
            loadFile.Close();
            System.IO.FileInfo fileInfo = new FileInfo(fileName);
            //存入DB
            dbContext.Files.Add(new BusinessSystemDBEntityModel.File
            {
                FileName = Path.GetFileNameWithoutExtension(fileName),
                //Data = filecontent,
                FileSize   = fileInfo.Length.ToString(),
                EmployeeID = LoginID,
                UploadDate = DateTime.Now,
                Extension  = Path.GetExtension(fileName)
            });
            //儲存修改
            dbContext.SaveChanges();
            //更新顯示
            MyUpdate();
        }
Esempio n. 16
0
        private string ReadPayload(string currentFile, ref long nextLineBeginsAtOffset, ref int count)
        {
            var events = new List <string>();

            using (var current = IOFile.Open(currentFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                current.Position = nextLineBeginsAtOffset;

                string nextLine;
                while (count < batchPostingLimit &&
                       TryReadLine(current, ref nextLineBeginsAtOffset, out nextLine))
                {
                    // Count is the indicator that work was done, so advances even in the (rare) case an
                    // oversized event is dropped
                    count++;

                    events.Add(nextLine);
                }
            }

            var payload = new StringWriter();

            batchFormatter.Format(events, payload);

            return(payload.ToString());
        }
Esempio n. 17
0
        public ActionResult ExportToExcel()
        {
            DataTable dt = Session["ExcelInput"] as DataTable;

            try
            {
                if (dt != null)
                {
                    ExcelHelper excelHelper = new ExcelHelper();
                    string      targetPath  = Path.Combine(Runbow.TWS.Common.Constants.UPLOAD_FOLDER_PATH, base.UserInfo.ProjectID.ToString(), "Temp");

                    string fileFullPath = Path.Combine(targetPath, "DataInExcel.xlsx");

                    excelHelper.CreateExcelByDataTable(fileFullPath, dt);

                    excelHelper.Dispose();

                    string mimeType = "application/msexcel";

                    FileStream fs = MyFile.Open(fileFullPath, FileMode.Open);

                    return(File(fs, mimeType, "DataInExcel.xlsx"));
                }

                return(RedirectToAction("Error", new { msg = "请重新登录" }));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Error", new { msg = ex.Message }));
            }
        }
Esempio n. 18
0
            public async Task <IHttpActionResult> Post(Update update)
            {
                var message = update.Message;

                Console.WriteLine("Received Message from {0}", message.Chat.Id);

                if (message.Type == MessageType.Text)
                {
                    // Echo each Message
                    await Bot.Api.SendTextMessageAsync(message.Chat.Id, message.Text);
                }
                else if (message.Type == MessageType.Photo)
                {
                    // Download Photo
                    var file = await Bot.Api.GetFileAsync(message.Photo.LastOrDefault()?.FileId);

                    var filename = file.FileId + "." + file.FilePath.Split('.').Last();

                    using (var saveImageStream = File.Open(filename, FileMode.Create))
                    {
                        await Bot.Api.DownloadFileAsync(file.FilePath, saveImageStream);
                    }

                    await Bot.Api.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
                }

                return(Ok());
            }
Esempio n. 19
0
        private static async Task RetrySendAudio(FileInfo file, int k, TimeSpan duration, MessageCategory messageCategory)
        {
            try
            {
                Bot = new TelegramBotClient(ApiToken);
                var me = Bot.GetMeAsync().Result;
                //Bot.StopReceiving();
                Bot.StartReceiving();
                Thread.Sleep(5000);
                var retryStream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                var fts         = new InputOnlineFile(retryStream);
                fts.FileName = file.FullName.Split('\\').Last();
                var title = fts.FileName + Environment.NewLine + "#" + messageCategory;
                title += Environment.NewLine + "#" + messageCategory + "No" + k;

                var result = await Bot.SendAudioAsync(ChatId, fts, duration : Convert.ToInt32(Math.Truncate(duration.TotalSeconds)), caption : fts.FileName, title : title);

                Utility.AppendToJsonFile(result, messageCategory);
            }
            catch (Exception ex)
            {
                Console.Write($"retry failed with message:{ex.Message}. retrying again ...");
                await RetrySendAudio(file, k, duration, messageCategory);
            }
        }
        public void Save()
        {
            FileStream streamFile = SystemIOFile.Open(FileName, FileMode.Create);

            XmlConstantsViewer.Serialize(streamFile, this);
            streamFile.Close();
        }
Esempio n. 21
0
        private static void SendAudioToChannel()
        {
            DirectoryInfo d = new DirectoryInfo(AudioFilesPath);

            FileInfo[] Files = d.GetFiles("*.mp3");
            foreach (FileInfo audioFile in Files)
            {
                var      filePath = AudioFilesPath + "\\" + audioFile.Name;
                string   fileExt  = Path.GetExtension(filePath);
                TimeSpan duration = new TimeSpan();
                if (fileExt == ".mp3")
                {
                    //Use NAudio to get the duration of the File as a TimeSpan object
                    duration = new Mp3FileReader(filePath).TotalTime;
                }

                using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    InputOnlineFile file = new InputOnlineFile(stream);
                    file.FileName = filePath.Split('\\').Last();

                    var test =
                        Bot.SendAudioAsync(ChatId, file, file.FileName, duration: duration.Seconds)
                        .GetAwaiter()
                        .GetResult();
                }
            }
        }
Esempio n. 22
0
        private static async Task RetrySendDocument(FileInfo file, int fileIndex, MessageCategory messageCategory)
        {
            try
            {
                Bot = new TelegramBotClient(ApiToken);
                var me = Bot.GetMeAsync().Result;
                //Bot.StopReceiving();
                Bot.StartReceiving();
                var retryStream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                var fts         = new InputOnlineFile(retryStream);

                fts.FileName = file.FullName.Split('\\').Last();
                var title = fts.FileName + Environment.NewLine + "#" + messageCategory;
                title += Environment.NewLine + "#" + messageCategory + "No" + fileIndex;
                Thread.Sleep(5000);
                var result = await Bot.SendDocumentAsync(ChatId, fts, title);

                Utility.AppendToJsonFile(result, messageCategory);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Retry failed with messag:{ex.Message}. trying again...");
                await RetrySendDocument(file, fileIndex, messageCategory);
            }
        }
Esempio n. 23
0
        private static bool IsUnlockedAtLength(string file, long maxLength)
        {
            try
            {
                using (var fileStream = IOFile.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                {
                    return(fileStream.Length <= maxLength);
                }
            }
#if HRESULTS
            catch (IOException ex)
            {
                var errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1);
                if (errorCode != 32 && errorCode != 33)
                {
                    SelfLog.WriteLine("Unexpected I/O exception while testing locked status of {0}: {1}", file, ex);
                }
            }
#else
            catch (IOException)
            {
                // Where no HRESULT is available, assume IOExceptions indicate a locked file
            }
#endif
            catch (Exception ex)
            {
                SelfLog.WriteLine("Unexpected exception while testing locked status of {0}: {1}", file, ex);
            }

            return(false);
        }
Esempio n. 24
0
        public void Save()
        {
            FileStream streamFile = SystemIOFile.Open(FileName, FileMode.Create);

            XmlAgreement.Serialize(streamFile, this);
            streamFile.Close();
        }
Esempio n. 25
0
        public GodotIdeServer(Action launchIdeAction, string editorExecutablePath, string projectMetadataDir)
            : base(projectMetadataDir)
        {
            messageHandlers = InitializeMessageHandlers();

            this.launchIdeAction = launchIdeAction;

            // The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing...
            const FileShare metaFileShare = FileShare.ReadWrite;

            metaFile = File.Open(MetaFilePath, FileMode.Create, FileAccess.Write, metaFileShare);

            listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port: 0));
            listener.Start();

            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;

            using (var metaFileWriter = new StreamWriter(metaFile, Encoding.UTF8))
            {
                metaFileWriter.WriteLine(port);
                metaFileWriter.WriteLine(editorExecutablePath);
            }

            StartServer();
        }
Esempio n. 26
0
        public FileInfo(string path)
        {
            BY_HANDLE_FILE_INFORMATION kernelFileInfo;
            bool result;

            using (var file = IOFile.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                try
                {
                    result = GetFileInformationByHandle(file.SafeFileHandle, out kernelFileInfo);
                }
                finally
                {
                    file.Close();
                }
            }

            if (!result)
            {
                throw new Win32Exception();
            }

            LinkCount          = kernelFileInfo.NumberOfLinks;
            VolumeSerialNumber = kernelFileInfo.VolumeSerialNumber;
            FileIndex          = kernelFileInfo.FileIndexHigh;
            FileIndex          = FileIndex << 32;
            FileIndex         |= kernelFileInfo.FileIndexLow;
        }
        /// <summary>
        ///     Searches for the assembly, interrogates it for it's providers and then proceeds to load
        /// </summary>
        /// <param name="request"></param>
        /// <param name="providerAssemblyName"></param>
        /// <returns></returns>
        internal bool TryToLoadProviderAssembly(string providerAssemblyName, IHostApi request)
        {
            request.Debug(request.FormatMessageString("Trying provider assembly: {0}", providerAssemblyName));

            var assemblyPath = FindAssembly(providerAssemblyName);

            if (assemblyPath != null)
            {
                try {
                    byte[] hash = null;
                    using (var stream = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                        hash = System.Security.Cryptography.MD5.Create().ComputeHash(stream);
                    }
                    lock (_providerFiles) {
                        if (_providerFiles.ContainsKey(assemblyPath))
                        {
                            // have we tried this file before?
                            if (_providerFiles[assemblyPath].SequenceEqual(hash))
                            {
                                // and it's the exact same file?
                                request.Debug(request.FormatMessageString("Skipping previously processed assembly: {0}", assemblyPath));
                                return(false);
                            }
                            request.Debug(request.FormatMessageString("New assembly in location: {0}", assemblyPath));
                            // it's a different file in the same path?
                            // we're gonna let it try the new file.
                            _providerFiles.Remove(assemblyPath);
                        }
                        else
                        {
                            request.Debug(request.FormatMessageString("Attempting loading of assembly: {0}", assemblyPath));
                        }

                        // record that this file is being loaded.
                        _providerFiles.Add(assemblyPath, hash);
                    }
                    if (AcquireProviders(assemblyPath, request))
                    {
                        request.Debug(request.FormatMessageString("SUCCESS provider assembly: {0}", providerAssemblyName));
                        return(true);
                    }
                } catch (Exception e) {
                    e.Dump();

                    lock (_providerFiles) {
                        // can't create hash from file?
                        // we're not going to try and load this.
                        // all we can do is record the name.
                        if (!_providerFiles.ContainsKey(assemblyPath))
                        {
                            _providerFiles.Add(assemblyPath, new byte[0]);
                        }
                    }
                }
            }
            request.Debug(request.FormatMessageString("FAILED provider assembly: {0}", providerAssemblyName));
            return(false);
        }
Esempio n. 28
0
        public override string Name => "picture";//some name to trigger command

        public override async Task <Message> Execute(Message message, CallbackQuery query)
        {
            var    chatId       = message.Chat.Id;
            string relativePath = String.Empty;

            try
            {
                string dir     = Directory.GetCurrentDirectory();
                var    counter = 0;
                for (int i = dir.Length; i > 0; i--)
                {
                    if (dir[i - 1].Equals('\\'))
                    {
                        counter++;
                        if (counter == 4)
                        {
                            break;
                        }
                    }

                    dir = dir.Remove(i - 1, 1);
                }

                relativePath = dir + "WebAppBot\\Resources\\honda-nsx_1.jpg";
                relativePath = relativePath.Replace(@"\", "/");
                using (FileStream fileStream = File.Open(relativePath, FileMode.Open))
                {
                    InputOnlineFile photo = new InputOnlineFile(fileStream);
                    photo.FileName = Path.GetFileName(relativePath);
                    if (photo.Content != null)
                    {
                        await Bot.BotClient.SendPhotoAsync(chatId, photo, "Car from disk");
                    }
                }
            }
            catch (Exception e)
            {
                //relativePath = "../../../Resources/honda-nsx_1.jpg";
            }


            string radomPhotoUrl = "https://source.unsplash.com/random";
            string onlyUrl       = "https://source.unsplash.com";
            var    httpClient    = new HttpClient();

            httpClient.BaseAddress = new Uri(onlyUrl);
            var response = await httpClient.GetAsync("/random");

            response.EnsureSuccessStatusCode();
            using (var responseStream = await response.Content.ReadAsStreamAsync())
            {
                InputOnlineFile randomPhoto = new InputOnlineFile(responseStream);
                await Bot.BotClient.SendPhotoAsync(chatId, randomPhoto, " Random Photo from stream ");
            }


            return(await Bot.BotClient.SendPhotoAsync(chatId, radomPhotoUrl, "Random photo!"));
        }
Esempio n. 29
0
        public static Stream ResolveUserStream(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite)
        {
            if (_userPath == null)
            {
                throw new InvalidOperationException("Must call SetAppInfo first!");
            }

            return(File.Open(Path.Combine(_userPath, path), mode, access));
        }
Esempio n. 30
0
        public Stream OpenFile(IFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            return(SysFile.Open(((File)file).BinaryPath, FileMode.Open, FileAccess.ReadWrite));
        }
Esempio n. 31
0
        private void TestSameCore(File memTempFile, File localTempFile, FileMode mode, FileAccess access, FileShare share)
        {
            Stream memStream = null, localStream = null;
            Exception memException = null, localException = null;
            try
            {
                memStream = memTempFile.Open(mode, access, share);
            }
            catch (Exception e)
            {
                memException = e;
            }
            try
            {
                localStream = localTempFile.Open(mode, access, share);
            }
            catch (Exception e)
            {
                localException = e;
            }
            if (memException != null || localException != null)
            {
                if (memStream != null) memStream.Dispose();
                if (localStream != null) localStream.Dispose();

                var anyException = (memException ?? localException).GetType();

                Assert.That(memException, Is.InstanceOf(anyException), string.Format("In-Memory ex was {0}, but file was: {1}",
                    memException != null ? memException.ToString() : "NULL",
                    localException != null ? localException.ToString() : "NULL"));

                Assert.That(localException, Is.InstanceOf(anyException), string.Format("Local file ex was {0}, but in mem was: {1}.",
                    localException != null ? localException.ToString() : "NULL",
                    memException != null ? memException.ToString() : "NULL"));

                if (!(memException.GetType() == anyException && localException.GetType() == anyException))
                    Console.WriteLine("Memory exception: " + (memException != null ? memException.GetType().Name : null) +
                                      " Local exception: " + (localException != null ? localException.GetType().Name : null));
                return;
            }
            if (memStream.CanWrite)
                memStream.WriteByte(99);
            if (localStream.CanWrite)
                localStream.WriteByte(99);
            memStream.Dispose();
            localStream.Dispose();

            using (memStream = memTempFile.OpenRead())
            using (localStream = localTempFile.OpenRead())
            {
                memStream.ReadToEnd().ShouldBe(localStream.ReadToEnd());
                localStream.Close();
                memStream.Close();
            }
        }
Esempio n. 32
0
 public void Open(string filename)
 {
     File = new File<FragTypeModel>();
     File.Open(filename);
 }
Esempio n. 33
0
 public void Open(string filename)
 {
     File = new File<DrawableModelDictionary>();
     File.Open(filename);
 }
Esempio n. 34
0
 public void Open(Stream stream)
 {
     File = new File<FragTypeModel>();
     File.Open(stream);
 }
Esempio n. 35
0
 public void Open(Stream stream)
 {
     File = new File<DrawableModelDictionary>();
     File.Open(stream);
 }