private bool SaveFileDetails(FileDetail objDet) { DbConnection(); SqlDataReader reader; using (con) { try { con.Open(); //read annual balance SqlCommand com = new SqlCommand("AddFileDetails", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@FileName", objDet.FileName); com.Parameters.AddWithValue("@FileContent", objDet.FileContent); reader = com.ExecuteReader(); reader.Read(); return(true); } catch (Exception) { return(false); } } }
public JsonResult DeleteFile(string id) { if (String.IsNullOrEmpty(id)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Result = "Error" })); } try { Guid guid = new Guid(id); FileDetail fileDetail = db.FileDetail.Find(guid); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } //Remove from database db.FileDetail.Remove(fileDetail); db.SaveChanges(); //Delete file from the file system var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), fileDetail.Id + fileDetail.Extension); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public async Task <JsonResult> DeleteFile(string id) { if (String.IsNullOrEmpty(id)) { return(Json(new { result = false, message = "Failure!" })); } try { Guid guid = new Guid(id); FileDetail fileDetail = _context.FileDetail.Find(guid); if (fileDetail == null) { return(Json(new { result = false, message = "Failure!" })); } _context.FileDetail.Remove(fileDetail); await _context.SaveChangesAsync(); var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads"); var path = Path.Combine(uploads, fileDetail.Id + fileDetail.Extension); if (System.IO.File.Exists(uploads)) { System.IO.File.Delete(uploads); } return(Json(new { result = true, message = "Success!" })); } catch (IOException ex) { return(Json(new { result = false, message = ex.Message })); } }
public async Task <ActionResult> Edit([Bind(Include = "TourPackageID,TourPackageTitle,Highlights,InclusionExclusion,TourDestination,SpecialNotes,TourCostPrice,TourSalesPrice,TourDiscountPrice,TotalNights,HotelStar,HotelInUse,DayWiseItienary,TearmsAndConditions,Allotment,Adults,Childrens,CreatedOn,DepartingDate,ValidityDate,DayOne,DayTwo,DayThree,DayFour,DayFive,DaySix,DaySeven,DayEight,DayNine,DayTen")] TourPackage tourPackage) { if (ModelState.IsValid) { //New Files for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), FileDetailsId = Guid.NewGuid(), TourPackageId = tourPackage.TourPackageID }; var path = Path.Combine(Server.MapPath("~/Images/packageImg/"), fileDetail.FileDetailsId + fileDetail.Extension); file.SaveAs(path); db.Entry(fileDetail).State = EntityState.Added; } } //tourPackage.ModifiedOn = DateTime.Now; db.Entry(tourPackage).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(tourPackage)); }
//尋找資料第一行 public bool FindRow(ISheet sheet, FileDetail fileDetail) { fileDetail.StartRow = 0; foreach (IRow row in sheet) { foreach (ICell col in row) { string cellContent = col.RichStringCellValue.String.Trim(); if (ImportHelper.FileTypeList().Values.Contains(cellContent)) { fileDetail.FileType = ImportHelper.FileTypeList().FirstOrDefault(v => v.Value == cellContent).Key; fileDetail.StartRow = row.RowNum; if (fileDetail.FileType == "電話通聯") { fileDetail.StartRow++; } return(true); } } } return(false); }
public static List <FileDetail> GetFileDetailList(string filelocation, List <FileDetails> Filelist, string FileCategory, bool EnableDeleteFlag) { List <FileDetail> lstFiles = new List <FileDetail>(); try { if (Filelist != null) { //string[] strContentArray = strItem.Split(new char[] { '|' }); foreach (var s in Filelist) { if (s.Category == FileCategory) { FileDetail fileDetail = new FileDetail(); fileDetail.FileId = s.FileId; fileDetail.PhysicalFileName = s.FileGuid; fileDetail.FileName = s.FileName; fileDetail.FilePath = "~/" + filelocation + "/" + s.FileGuid; fileDetail.DeleteFlag = EnableDeleteFlag; lstFiles.Add(fileDetail); } } } } catch (Exception ex) { throw new RaveHRException(ex.Message, ex, Sources.DataAccessLayer, clsCommonRepository, "GetCourseContentDetails", RMS.Common.Constants.EventIDConstants.TRAINING_DATA_ACCESS_LAYER); } finally { } return(lstFiles); }
public static List <FileDetail> GetFileDetailList(string filelocation, string strItem) { List <FileDetail> lstFiles = new List <FileDetail>(); try { if (strItem != "") { string[] strContentArray = strItem.Split(new char[] { '|' }); foreach (string s in strContentArray) { FileDetail fileDetail = new FileDetail(); fileDetail.PhysicalFileName = s; fileDetail.FileName = s.Substring(s.IndexOf("_") + 1, (s.Length - (s.IndexOf("_") + 1))); fileDetail.FilePath = "~/" + filelocation + "/" + s; lstFiles.Add(fileDetail); } } } catch (Exception ex) { throw new RaveHRException(ex.Message, ex, Sources.DataAccessLayer, clsCommonRepository, "GetCourseContentDetails", RMS.Common.Constants.EventIDConstants.TRAINING_DATA_ACCESS_LAYER); } finally { } return(lstFiles); }
public IActionResult Index() { string path = @"C:\Users\SuleM\Downloads\Loggings\Loggings"; string line; string[] filePaths = Directory.GetFiles(path);//, SearchOption.AllDirectories List <string> errors = new(); foreach (var filePath in filePaths) { using (var sr = System.IO.File.OpenText(filePath)) { while ((line = sr.ReadLine()) != null) { var errorMessage = LogUtil.GetErrorMessage(line); errors.Add(errorMessage); } } } var errorDetails = new FileDetail(); var duplicates = LogUtil.GetDuplicates(errors); var uniques = LogUtil.GetNumberOfUniqueErrors(errors); errorDetails.NumberOfDuplicateErrors = duplicates.Count; errorDetails.NumberOfUniqueErrors = uniques.Count; ViewBag.Errors = duplicates; ViewBag.ErrorCount = errorDetails; return(View(errorDetails)); }
public ActionResult <FileDetail> GetLogsDupAndUniqCount(string path) { string line; string[] filePaths = Directory.GetFiles(path);//, SearchOption.AllDirectories if (filePaths is null) { return(NotFound()); } List <string> errors = new(); foreach (var filePath in filePaths) { using (var sr = System.IO.File.OpenText(filePath)) { while ((line = sr.ReadLine()) != null) { var errorMessage = LogUtil.GetErrorMessage(line); errors.Add(errorMessage); } } } var errorDetails = new FileDetail(); var duplicates = LogUtil.GetDuplicates(errors); var uniques = LogUtil.GetNumberOfUniqueErrors(errors); errorDetails.NumberOfDuplicateErrors = duplicates.Count; errorDetails.NumberOfUniqueErrors = uniques.Count; return(errorDetails); }
public JsonResult DeleteFile(int id) { try { FileDetail fileDetail = db.FileDetails.Where(x => x.FileDetailID == id).FirstOrDefault(); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } //Remove from database var pathSub = Path.Combine(Server.MapPath("~/Img/"), fileDetail.ProductID + "_" + fileDetail.FileDetailID + "_" + fileDetail.FileName); if (System.IO.File.Exists(pathSub)) { System.IO.File.Delete(pathSub); } db.FileDetails.Remove(fileDetail); db.SaveChanges(); //Delete file from the file system return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public ActionResult Edit([Bind(Include = "MajorId,Name,MetaTitle,Description,CreateDate,CreateBy,ModifyDate,ModifyBy")] Major major, HttpPostedFileBase uploadFile) { if (ModelState.IsValid) { FileUploadService service = new FileUploadService(); var session = (UserLogin)Session[CommonConstants.USER_SESSION]; if (uploadFile != null) { FileDetail file = db.FileDetails.ToList().Find(x => x.MajorId == major.MajorId); if (file != null) { file.FileName = Path.GetFileName(uploadFile.FileName); file.ContentType = uploadFile.ContentType; file.Data = service.ConvertToBytes(uploadFile); db.Entry(file).State = EntityState.Modified; } else { db.FileDetails.Add(new FileDetail { FileName = Path.GetFileName(uploadFile.FileName), ContentType = uploadFile.ContentType, Data = service.ConvertToBytes(uploadFile), MajorId = major.MajorId }); } } major.ModifyBy = session.Username; major.ModifyDate = DateTime.Now; db.Entry(major).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(major)); }
public ActionResult CreateFile(Patients patients, List <HttpPostedFileBase> postedFiles) { string path = Server.MapPath("~/Uploads/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } foreach (HttpPostedFileBase postedFile in postedFiles) { if (postedFile != null) { string fileName = Path.GetFileName(postedFile.FileName); postedFile.SaveAs(path + fileName); ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid(), IdPatients = patients.IdPatients }; db.FileDetails.Add(fileDetail); db.SaveChanges(); ViewBag.IdPatients = new SelectList(db.Patients, "IdPatients", "IdPatients", fileDetail.IdPatients); } } return(View()); }
void safeDeleteFile(FileDetail dupe, string masterFullPathName, string delCandidate, string note, long fileSize, bool makeSureIsCameraRollOrAlike = true) { if (!File.Exists(masterFullPathName)) { throw new Exception("master does not exist."); } //if (!(masterFullPathName.Contains(_MasterSignature) && (!masterFullPathName.Contains(_DoubleSignature) && !delCandidate.Contains(DoubleFolder)))) throw new Exception("Does not look like the master is in the right place: possibly deleting from the master instead of dupe location."); if (makeSureIsCameraRollOrAlike) { if (delCandidate.Contains(_MasterSignature) && !delCandidate.Contains(_DoubleSignature)) { throw new Exception("DelCandidate does not belong to to-be-deleted-folder"); } } #if DEBUG Trace.WriteLine($"Deleting: {delCandidate}\r\n Master: {masterFullPathName}"); synth.Speak($"Deletion suspended for Debug mode."); #else File.Delete(delCandidate); #endif smartUpdateNote(dupe, string.Format(note, masterFullPathName)); _TtlBytesDeleted += fileSize; _TotalDeleted++; }
public IEnumerable <FileDetail> MockListFileDetailOfTruckDriverDocuments() { var listFileDetail = new FileDetail[] { new FileDetail() { TruckDriverDocId = 1, FileId = Guid.Parse("1A3B944E-3632-467B-A53A-206305310BAE"), FileName = "DriverA_DriverLicence", Extension = ".pdf", FileCategory = "Driver Licence", LastModified = new DateTime(2017, 8, 12, 5, 50, 30) }, new FileDetail() { TruckDriverDocId = 1, FileId = Guid.Parse("a2c11e77-06ff-48da-9514-8bc2b3bfdb27"), FileName = "DriverA_CitizenId", Extension = ".pdf", FileCategory = "CitizenId", LastModified = new DateTime(2017, 12, 4, 3, 24, 30) } }; return(listFileDetail); }
/// <summary> /// Uploads the associated file to temporary container. /// </summary> /// <param name="fileDetail">Details of the associated file.</param> /// <returns>True if content is uploaded; otherwise false.</returns> public OperationStatus UploadTemporaryFile(FileDetail fileDetail) { OperationStatus operationStatus = null; // Make sure file detail is not null this.CheckNotNull(() => new { fileDetail }); var fileBlob = new BlobDetails() { BlobID = fileDetail.AzureID.ToString(), Data = fileDetail.DataStream, MimeType = fileDetail.MimeType }; try { _blobDataRepository.UploadTemporaryFile(fileBlob); operationStatus = OperationStatus.CreateSuccessStatus(); } catch (Exception) { operationStatus = OperationStatus.CreateFailureStatus(Resources.UnknownErrorMessage); } return(operationStatus); }
/// <summary> /// Move Home video from temp to correct container. /// </summary> /// <param name="fileDetails">Details of the video.</param> public OperationStatus MoveTempFile(FileDetail fileDetails) { OperationStatus operationStatus = null; this.CheckNotNull(() => new { fileDetails }); // Move Home video. if (fileDetails.AzureID != null) { // Move the video file from temporary container to file container. try { if (MoveAssetFile(fileDetails)) { operationStatus = OperationStatus.CreateSuccessStatus(); } else { operationStatus = OperationStatus.CreateFailureStatus(Resources.UnknownErrorMessage); } } catch (Exception) { operationStatus = OperationStatus.CreateFailureStatus(Resources.UnknownErrorMessage); } } return(operationStatus); }
public ActionResult Edit(Magazine magazine, string receiver) { if (ModelState.IsValid) { //New Files for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid(), MagazineID = magazine.MagazineID }; var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), fileDetail.Id + fileDetail.Extension); file.SaveAs(path); db.Entry(fileDetail).State = EntityState.Added; } } ViewBag.TopicID = new SelectList(db.Topics, "TopicID", "TopicName", magazine.TopicID); db.Entry(magazine).State = EntityState.Modified; db.SaveChanges(); string subject = "Your student has Delete their post submission for your Topic"; string body = "Hi Marketing Coordinator," + "Your student has editted their post submission for your Topic: " + magazine.TopicName + " Student's name: " + User.Identity.Name + " Submit Date: " + DateTime.Now; WebMail.Send(receiver, subject, body); return(RedirectToAction("Index")); } return(View(magazine)); }
/// <summary> /// Uploads file to azure. /// </summary> /// <param name="fileDetails">Details of the file.</param> public OperationStatus UploadAsset(FileDetail fileDetails) { OperationStatus operationStatus = null; this.CheckNotNull(() => new { fileDetails }); var fileBlob = new BlobDetails() { BlobID = fileDetails.Name, Data = fileDetails.DataStream, MimeType = fileDetails.MimeType }; try { if (_blobDataRepository.UploadAsset(fileBlob)) { operationStatus = OperationStatus.CreateSuccessStatus(); } else { operationStatus = OperationStatus.CreateFailureStatus(Resources.UnknownErrorMessage); } } catch (Exception) { operationStatus = OperationStatus.CreateFailureStatus(Resources.UnknownErrorMessage); } return(operationStatus); }
public async Task <IActionResult> Get(string id) { try { if (Guid.TryParse(id, out Guid parsedId)) { FileDetail fileDetail = null; fileDetail = await _unitOfWork.FileDetails.GetFileDetailWithRelationsAsync(parsedId, true); if (fileDetail == null) { fileDetail = await _unitOfWork.FileDetails.GetDetailWithRelationsAsync(parsedId, true); } if (fileDetail != null) { return(Ok(_mapper.Map <FileDet>(fileDetail))); } } } catch (Exception e) { string message = e.Message; } return(NotFound()); }
public async Task <FileDetail> SaveFile(IFormFile file, string apiVersion) { var _result = new FileDetail(); //====== _result.DocType = Path.GetExtension(file.FileName); var _request = _httpContextAccessor.HttpContext.Request; var _baseUrl = $"{_request.Scheme}://{_request.Host.Value}"; if (new string[] { ".pdf", ".jpg", ".png", ".jpeg" }.Contains(_result.DocType.Trim().ToLower())) { var _docName = Path.GetFileName(file.FileName); _result.FileName = _docName; if (file?.Length > 0) { var _destination = Path.Combine(_basePath, _docName); _result.DocUrl = $"{_baseUrl}/{apiVersion}/file/{_result.FileName}"; using (var stream = new FileStream(_destination, FileMode.Create)) { await file.CopyToAsync(stream); } } } //====== return(_result); }
public FileDetail Add(HttpPostedFileBase upload, string saveDirectory) { if (upload == null || upload.ContentLength == 0) { throw new ArgumentNullException(nameof(upload)); } var guid = Guid.NewGuid(); var newFileName = guid + Path.GetExtension(upload.FileName); var file = new FileDetail { Id = guid, ContentType = upload.ContentType, OriginalFileName = Path.GetFileName(upload.FileName), FileName = newFileName, FilePath = Path.Combine(saveDirectory, newFileName) }; upload.SaveAs(file.FilePath); this.UnitOfWork.FileDetails.Add(file); this.UnitOfWork.Commit(); return(file); }
public JsonResult DeleteFile(int?id) { if (id == null) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Result = "Error" })); } try { FileDetail fileDetail = db.FileDetails.Find(id); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } //Remove from database db.FileDetails.Remove(fileDetail); db.SaveChanges(); return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
public ActionResult Delete(int?id) { ApplicationDbContext db = new ApplicationDbContext(); ApplicationDbContext dr = new ApplicationDbContext(); FileDetail fileToDelete = db.FileDetails.Find(id); VMFileDetail fd = new VMFileDetail(); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } else { if (fileToDelete == null) { return(HttpNotFound()); } else { fd.Id = fileToDelete.Id; fd.UserId = fileToDelete.UserId; fd.UserName = dr.Users.Where(user => user.Id == fd.UserId).FirstOrDefault().FullName; fd.FileName = fileToDelete.FileName; fd.DateProcessed = fileToDelete.DateProcessed; } } return(View("~/Views/Documents/Processed/Delete.cshtml", fd)); }
public void Execute_ValidationFails_ThrowsException() { int projectId = new Random().Next(1, 1000); string filePath = Path.Combine(AppContext.BaseDirectory, "test.log"); FileDetail fileDetail = new FileDetail(); fileDetail.Hash = Guid.NewGuid().ToString(); _fileUtils.GetFileHash(filePath).Returns(fileDetail); _logFileValidator.Validate(Arg.Any <LogFileModel>()).Returns(new ValidationResult("error")); // execute TestDelegate del = () => _createLogFileCommand.Execute(projectId, filePath); // assert Assert.Throws <ValidationException>(del); _fileUtils.Received(1).GetFileHash(filePath); _logFileRepo.Received(1).GetByHash(projectId, fileDetail.Hash); _logFileValidator.Received(1).Validate(Arg.Any <LogFileModel>()); // we shouldn't have tried to do the insert _dbContext.DidNotReceive().ExecuteNonQuery(Arg.Any <string>(), Arg.Any <object>()); }
public void Execute_ValidationSucceeds_RecordInsertedAndJobRegistered() { int projectId = new Random().Next(1, 1000); string filePath = Path.Combine(AppContext.BaseDirectory, "test.log"); FileDetail fileDetail = new FileDetail(); fileDetail.Length = new Random().Next(1000, 10000); fileDetail.Hash = Guid.NewGuid().ToString(); fileDetail.Name = Guid.NewGuid().ToString(); _fileUtils.GetFileHash(filePath).Returns(fileDetail); _logFileValidator.Validate(Arg.Any <LogFileModel>()).Returns(new ValidationResult()); // execute LogFileModel result = _createLogFileCommand.Execute(projectId, filePath); // assert _dbContext.Received(1).ExecuteNonQuery(Arg.Any <string>(), Arg.Any <object>()); _dbContext.Received(1).ExecuteScalar <int>(Arg.Any <string>()); _jobRegistrationService.Received(1).RegisterProcessLogFileJob(result.Id, filePath); Assert.AreEqual(projectId, result.ProjectId); Assert.AreEqual(fileDetail.Hash, result.FileHash); Assert.AreEqual(fileDetail.Length, result.FileLength); Assert.AreEqual(fileDetail.Name, result.FileName); Assert.AreEqual(-1, result.RecordCount); Assert.AreEqual(LogFileStatus.Processing, result.Status); }
public ActionResult Create(Patients patient) { if (ModelState.IsValid) { List <FileDetail> fileDetails = new List <FileDetail>(); for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid() }; fileDetails.Add(fileDetail); var path = Path.Combine(Server.MapPath("~/Uploads/"), fileDetail.Id + fileDetail.Extension); file.SaveAs(path); } } patient.FileDetails = fileDetails; db.Patients.Add(patient); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(patient)); }
public ActionResult Edit(System_Form system_Form) { if (ModelState.IsValid) { //New Files for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid(), Form_id = system_Form.Form_id }; var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), fileDetail.Id + fileDetail.Extension); file.SaveAs(path); db.Entry(fileDetail).State = EntityState.Added; } } db.Entry(system_Form).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(system_Form)); }
public ActionResult Edit(Support support) { fillUserData(); if (ModelState.IsValid) { //New Files for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), Id = Guid.NewGuid(), SupportId = support.SupportId }; var path = Path.Combine(Server.MapPath("~/Images/"), fileDetail.Id + fileDetail.Extension); file.SaveAs(path); db.Entry(fileDetail).State = EntityState.Added; } } db.Entry(support).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("EmployeeDocs", new { Employeeid = support.EmpId })); } return(View(support)); }
public ActionResult Details(string id) { FileDetail filed = new FileDetail(); if (db.File.Where(m => m.FID.Equals(id)).Count() > 0) { filed.file = db.File.ToList().Select(m => new FileViewModel() { FID = m.FID, Name = m.Name, FromId = m.FromUID, Pub = m.Pub, UploadTime = m.UploadTime.ToString("yyyy/MM/dd"), Type = m.Type, Size = m.Size, DownloadTimes = m.DownloadTimes, FromUID = UserManager.FindById(m.FromUID).RealName }).First(); List <string> ToUIDs = db.DownUpload.Where(m => m.FID.Equals(id)).Select(m => m.ToUID).ToList(); filed.Receives = UserManager.Users.ToList().Where(m => ToUIDs.Contains(m.Id)).ToList(); return(View(filed)); } return(new HttpNotFoundResult()); }
public async Task <IActionResult> Create(IFormFile file, string contenttype, string filename, string filetype, int orderid) { //FileDetail fileDetail = new FileDetail(files, contenttype, filename, filetype, orderid); //List<IFormFile> files, string contenttype, string filename, string filetype, int orderid byte[] fileBytes = null; //opening filestream and them using MemoryStream to get an array of bytes if (file.Length > 0) { using (var fileStream = file.OpenReadStream()) using (var ms = new MemoryStream()) { fileStream.CopyTo(ms); fileBytes = ms.ToArray(); } } FileDetail fileDetail = new FileDetail(); fileDetail.File = fileBytes; fileDetail.ContentType = contenttype; fileDetail.FileName = filename; fileDetail.FileType = filetype; fileDetail.OrderID = orderid; if (ModelState.IsValid) { _context.Add(fileDetail); await _context.SaveChangesAsync(); sp_Logging("2-Change", "Create", "User uploaded a File where Filename=" + filename + " and Order# is " + orderid, "Success"); return(RedirectToAction("Index")); } ViewData["OrderID"] = new SelectList(_context.Orders, "OrderID", "OrderID", fileDetail.OrderID); return(View(fileDetail)); }
private void addDirectory(Dictionary<string, FileDetail> localFiles, int relativePathStart, DirectoryInfo directory) { FileDetail detail; foreach (FileInfo file in directory.GetFiles()) { detail = new FileDetail(file.FullName.Substring(relativePathStart), file.Length, file.LastWriteTimeUtc); localFiles[detail.RelativePath] = detail; } foreach (DirectoryInfo child in directory.GetDirectories()) { addDirectory(localFiles, relativePathStart, child); } }
public Archive(FileDetail detail) : base(detail.RelativePath, detail.FileLength, detail.LastModified) { ArchiveDescription = DateFormat.formatDateTime(detail.LastModified, true) + "," + detail.FileLength + "," + detail.RelativePath; Size = detail.FileLength; }
public FileDetail WriteRandomTxtFile(FileDetail fileDetail) { File.Write(fileDetail); return fileDetail; }