/// <summary>
 /// Метод создающий файл если тот не был создан ранее
 /// </summary>
 protected virtual void CreateFileIfNotExists()
 {
     if (!File.Exists(Path))
     {
         File.Create(Path).Close();
     }
 }
        public IActionResult Upload(IFormCollection form)
        {
            var stl        = form.Files[0];
            var subpath    = "/uploads/" + Guid.NewGuid().ToString() + ".stl";
            var filePath   = Startup._env.WebRootPath + subpath;
            var fileStream = FILE.Create(filePath);

            var stream = stl.OpenReadStream();

            stream.Seek(0, System.IO.SeekOrigin.Begin);
            stream.CopyTo(fileStream);
            stream.Close();
            fileStream.Close();

            var model = new UploadModel()
            {
                dt       = DateTime.Now,
                subpath  = subpath,
                filename = stl.FileName,
            };

            model.FillStlInfo(filePath);

            var id = db.Uploads.Insert(model);

            return(Json(new { id = id.AsString }));
        }
 /// <summary>
 /// Check if the file exist if the file does not exist is created
 /// </summary>
 /// <param name="filePath">The file path</param>
 private void CheckFile(string filePath)
 {
     if (!IoFile.Exists(filePath))
     {
         IoFileStream stream = IoFile.Create(filePath);
         stream.Close();
     }
 }
Beispiel #4
0
        /// <summary>
        /// Проверяет наличие файлов с данными БД
        /// </summary>
        /// <param name="dataPath">
        /// Путь до папки, где должеы лежать искомые файлы
        /// </param>
        /// <param name="isFilesEmpty">
        /// true - если оба файла пустые, иначе false
        /// </param>
        private void CheckJSONFiles()
        {
            if (File.Exists(imagesFile) && File.Exists(objectClassesFile) && File.Exists(sessionsFile))
            {
                //считываем из файликов данные
                Images        = JsonConvert.DeserializeObject <List <Image> >(File.ReadAllText(imagesFile));
                ObjectClasses = JsonConvert.DeserializeObject <List <ObjectClass> >(File.ReadAllText(objectClassesFile));
                Sessions      = JsonConvert.DeserializeObject <List <Session> >(File.ReadAllText(sessionsFile));

                if (Images == null && (Sessions != null))
                {
                    throw new DatabaseException("Файл imagesData.json пуст!");
                }
                else if (Images == null && ObjectClasses == null)
                {
                    Images        = new List <Image>();
                    ObjectClasses = new List <ObjectClass>();
                }
                else if (Images != null && ObjectClasses == null)
                {
                    ObjectClasses = new List <ObjectClass>();
                }

                if (Sessions == null)
                {
                    Sessions = new List <Session>();
                }
            }
            else
            {
                //создаем недостающие файлы, оставляя их пустыми (!)

                if (!File.Exists(imagesFile))
                {
                    using (File.Create(imagesFile))
                    { }

                    Images = new List <Image>();
                }

                if (!File.Exists(objectClassesFile))
                {
                    using (File.Create(objectClassesFile))
                    { }

                    ObjectClasses = new List <ObjectClass>();
                }

                if (!File.Exists(sessionsFile))
                {
                    using (File.Create(sessionsFile))
                    { }

                    Sessions = new List <Session>();
                }
            }
        }
Beispiel #5
0
        public void Save(ImageSaveRequest request)
        {
            var fileNamePath = _storePath + request.Entity.imageId + "." + request.Entity.extension;

            using (var file = SysFile.Create(fileNamePath))
            {
                request.ImageStream.CopyTo(file);
                file.Close();
                request.ImageStream.Close();
            }
        }
Beispiel #6
0
        public void CanUploadBigFileToAppResult_MultiPart()
        {
            var project   = TestHelpers.CreateRandomTestProject(Client);
            var appResult = TestHelpers.CreateRandomTestAppResult(Client, project);
            var file      = File.Create(string.Format("UnitTestFile_{0}", appResult.Id));

            file.Write(new byte[31000000], 0, 31000000);
            file.Close();
            var response = Client.UploadFileToAppResult(new UploadFileToAppResultRequest(appResult.Id, file.Name), null);

            Assert.NotNull(response);
            Assert.True(response.Response.UploadStatus == FileUploadStatus.complete);
        }
 /// <summary>
 /// Check if the file exist if the file does not exist is created
 /// </summary>
 /// <param name="filePath">The file path</param>
 private void CheckFile(string filePath)
 {
     try
     {
         if (!IoFile.Exists(filePath))
         {
             IoFile.Create(filePath).Close();
         }
     }
     catch (Exception exc)
     {
         throw exc.CreateNamelessException <GodModeException>(ERR_CREATING_FILE);
     }
 }
        public IActionResult Index(IFormCollection form, IFormFile stl)
        {
            var filepath   = "/tmp/" + Guid.NewGuid().ToString() + ".bin";
            var path       = Startup._env.WebRootPath + filepath;
            var fileStream = FILE.Create(path);

            var stream = stl.OpenReadStream();

            stream.Seek(0, System.IO.SeekOrigin.Begin);
            stream.CopyTo(fileStream);
            stream.Close();
            fileStream.Close();

            TempData["stlfile"] = filepath;
            return(RedirectToAction("StlViewer", new { path = filepath }));
        }
Beispiel #9
0
        private string CreateRandomFile(int size)
        {
            var filename = Guid.NewGuid().ToString();

            var r = new Random();

            using (var stream = F.Create(filename))
            {
                var bytes = new byte[size];
                r.NextBytes(bytes);

                stream.Write(bytes, 0, size);
                stream.Close();
            }

            return(filename);
        }
Beispiel #10
0
        internal void Actual_ShouldCompileWithResource()
        {
            var    outputFileLocation = rootFolder + "\\temp.exe";
            string resourceDirectory  = rootFolder + "\\WithReference\\CSharp";
            string resourceFile       = resourceDirectory + "\\test.resource";

            System.IO.Directory.CreateDirectory(resourceDirectory);
            File.Create(resourceFile).Dispose();

            Task.Build.Csc.Target.Library(x => x.AddSources(GetBasicSources())
                                          .AddResource(resourceFile)
                                          .OutputFileTo(outputFileLocation));
            Assert.That(File.Exists(outputFileLocation));

            Assembly assembly = Assembly.Load(File.ReadAllBytes(outputFileLocation));

            Assert.That(assembly.GetManifestResourceNames().Contains("test.resource"), Is.True);
        }
Beispiel #11
0
 public static bool CanWriteInCurrentDirectory()
 {
     if (canWriteInCurrentDirectory == null)
     {
         string path = P.Combine(D.GetCurrentDirectory(), Guid.NewGuid().ToString());
         try
         {
             using (F.Create(path)) { }
             F.Delete(path);
             canWriteInCurrentDirectory = true;
         }
         catch
         {
             canWriteInCurrentDirectory = false;
         }
     }
     return(canWriteInCurrentDirectory.Value);
 }
        private void PopulateConfig()
        {
            using (_ = SFile.Create(_configPath)) {}

            var err = _config.Load(_configPath);

            if (err == Error.Ok)
            {
                foreach (var key in DefaultSettings.Keys)
                {
                    _config.SetValue(SECTION, StringSettingsEntry(key), DefaultSettings[key]);
                }
                _config.Save(_configPath);
            }
            else
            {
                Log.Logger.Error("Failed to populate config");
            }
        }
        private async Task ProcessPhotoMessage(Message message)
        {
            var biggestPhoto = message.Photo.OrderByDescending(x => x.Width).FirstOrDefault();

            if (biggestPhoto == null)
            {
                return;
            }

            var filePath = $@"content\{Guid.NewGuid()}{DateTime.Now:dd.MM.yyyy_HH.mm.ss}.png";

            using (var stream = File.Create($@"C:\apps\fserver\{filePath}"))
            {
                await bot.GetFileAsync(biggestPhoto.FileId, stream);

                stream.Flush();
            }

            string url = $@"http://185.117.154.233:3579/{filePath.Replace(@"\", "/")}";

            pipboy.Debug(url);
            await bot.SendTextMessageAsync(SettingsStore.Settings["chatId"], url);
        }
        public static Dictionary <string, ShopUserModel> GetAllUsers()
        {
            if (cachedShopUserModels != null)
            {
                return(cachedShopUserModels);
            }

            if (!File.Exists(FilePath))
            {
                File.Create(FilePath);
            }

            var file = File.ReadAllText(FilePath);

            cachedShopUserModels = JsonConvert.DeserializeObject <Dictionary <string, ShopUserModel> >(file);

            if (cachedShopUserModels == null)
            {
                cachedShopUserModels = new Dictionary <string, ShopUserModel>();
            }

            return(cachedShopUserModels);
        }
        public IActionResult UploadImage(IFormFile image)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Upload Image Error."));
            }

            var message = "Image Name: " + image.Name + Environment.NewLine;

            message += "Image FileName: " + image.FileName + Environment.NewLine;
            message += "Image ContentType: " + image.ContentType + Environment.NewLine;
            message += "Image ContentDisposition: " + image.ContentDisposition + Environment.NewLine;

            using (var file = SysFile.Create("image.jpg"))
            {
                image.OpenReadStream().CopyTo(file);
                file.Close();
            }

            LogService.Info <NoteController>(message);

            return(Ok("Upload Image."));
        }