public ChaperoneFormModel GetChaperoneFormModel(long eventCustomerId) { var chaperoneSignature = _chaperoneSignatureRepository.GetByEventCustomerId(eventCustomerId); var staffSignatureFile = chaperoneSignature != null?_fileRepository.GetById(chaperoneSignature.StaffSignatureFileId) : null; if (staffSignatureFile == null) { return(new ChaperoneFormModel { EventCustomerId = eventCustomerId, CustomerAnswers = null, PatientSignatureBytes = null, }); } var chaperoneQuestions = _chaperoneQuestionRepository.GetAllQuestions(); var chaperoneAnswers = _chaperoneAnswerRepository.GetByEventCustomerId(eventCustomerId); var eventCustomer = _eventCustomerRepository.GetById(eventCustomerId); var mediaLocation = _mediaRepository.GetChaperoneSignatureLocation(eventCustomer.EventId, eventCustomer.CustomerId); string signatureFilePath = string.Empty; var signatureFile = chaperoneSignature != null && chaperoneSignature.SignatureFileId.HasValue ? _fileRepository.GetById(chaperoneSignature.SignatureFileId.Value) : null; if (signatureFile != null) { signatureFilePath = Path.Combine(mediaLocation.PhysicalPath, signatureFile.Path); } var staffSignatureFilePath = Path.Combine(mediaLocation.PhysicalPath, staffSignatureFile.Path); var chaperoneFormModel = new ChaperoneFormModel(); chaperoneFormModel.EventCustomerId = eventCustomerId; chaperoneFormModel.CustomerAnswers = chaperoneAnswers .Select(x => new ChaperoneAnswerModel { QuestionId = x.QuestionId, Answer = x.Answer }) .ToArray(); if (!string.IsNullOrEmpty(signatureFilePath) && File.Exists(signatureFilePath)) { var signatureFileByte = File.ReadAllBytes(signatureFilePath); chaperoneFormModel.PatientSignatureBytes = Convert.ToBase64String(signatureFileByte); } if (File.Exists(staffSignatureFilePath)) { var staffSignatureFileByte = File.ReadAllBytes(staffSignatureFilePath); chaperoneFormModel.StaffSignatureBytes = Convert.ToBase64String(staffSignatureFileByte); } return(chaperoneFormModel); }
private void label1_DragDrop(object sender, DragEventArgs e) { var a = listBox1.SelectedItem as UpdService.Objects.App; if (a == null) { return; } string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; foreach (string file in files) { if (!File.Exists(file)) { continue; } var f = Path.GetFileName(file); if (MessageBox.Show($"Загрузить {f} ?", "", MessageBoxButtons.YesNo) != DialogResult.Yes) { continue; } var bb = File.ReadAllBytes(file); wc.UploadData(Server + $"/Files/Load/{a.Id}/{f}", bb); } Form1_Load(null, null); }
public async Task PredefinedTmLeverageData() { var groupShareClient = Helper.GsClient; var filters = new PredefinedReportsFilters { ShowAll = true, Status = 7 }; var projectTemplate = groupShareClient.Project.GetAllTemplates().Result.ToList().FirstOrDefault(); var ProjectTemplateId = projectTemplate != null ? projectTemplate.Id : string.Empty; var rawData = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Grammar.zip")); var projectName = $"Project - {Guid.NewGuid()}"; var projectId = await groupShareClient.Project.CreateProject(new CreateProjectRequest( projectName, Helper.OrganizationId, null, DateTime.Now.AddDays(2), ProjectTemplateId, rawData)); var statusInfo = await WaitForProjectCreated(projectId); Assert.True(statusInfo); var reportingData = await groupShareClient.Reporting.PredefinedTmLeverage(filters); Assert.True(reportingData.Count > 0); await Helper.GsClient.Project.DeleteProject(projectId.ToString()); }
private void btnAddFile_Click(object sender, EventArgs e) { try { using (var dialog = new OpenFileDialog()) { if (dialog.ShowDialog() == DialogResult.OK) { var fileContent = File.ReadAllBytes(dialog.FileName); var file = new Model.File { Name = Path.GetFileName(dialog.FileName), Owner = _client.GetUser() }; var fileId = _client.CreateFile(file); _client.UploadFileContent(fileId, fileContent); RefreshFileList(); MessageBox.Show($"File {file.Name} was added successfully", "File Download", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception exception) { MessageBox.Show($"File was not added. Error message: {Environment.NewLine}{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void Pack(PackOptions options) { var directories = Directory.GetDirectories(options.Source); var writer = new ArchiveWriter(); foreach (var dir in directories) { var directoryName = Path.GetFileNameWithoutExtension(dir).Split(GroupIdSeparator); var groupNo = Convert.ToByte(directoryName[0]); var id = Convert.ToUInt16(directoryName[1]); var filesInside = Directory.GetFiles(dir); var group = new ManagedGroup() { Id = id, Files = new List <ManagedFile>(filesInside.Length) }; foreach (var file in filesInside) { group.Files.Add(new ManagedFile() { Data = File.ReadAllBytes(file) }); } writer.AddGroup(groupNo, group); } // Write file to new location. Directory.CreateDirectory(Path.GetDirectoryName(options.SavePath)); using var fileStream = new FileStream(options.SavePath, FileMode.Create, FileAccess.Write, FileShare.None); writer.Write(fileStream, options.BigEndian); }
public FileDTO LoadFileFromDisk(string path) { var info = new FileInfo(path); var content = IOFile.ReadAllBytes(info.FullName); return(new FileDTO(info.Name, content)); }
static void Bundle(bool run = true) { List <string> files = Directory.GetFiles("../../../Core", "*.dll").ToList(); files.AddRange(Directory.GetFiles("./", "*.txt")); PhysicalFileSystem fileSystem = new PhysicalFileSystem("../../../dev/"); fileSystem.CreateDirectory(FileSystemPath.Parse("/system/")); foreach (string file in files) { if (!file.Contains("MyOS.")) { using (Stream fileStream = fileSystem.CreateFile(FileSystemPath.Parse("/system/" + new FileInfo(file).Name.Replace(".dll", ".mye").Replace(".txt", ".ini")))) { byte[] fileBytes = File.ReadAllBytes(file); fileStream.Write(fileBytes, 0, fileBytes.Length); } Console.WriteLine("Written {0}", new FileInfo(file).Name.Replace(".dll", ".mye").Replace(".txt", ".ini")); } } Console.WriteLine("Done"); if (run) { //process.Kill(); //process.Start(); } }
private void PictureBox_DragDrop(object sender, DragEventArgs e) { object j = e.Data.GetData(DataFormats.FileDrop); string[] jStrings = (string[])j; Data = File.ReadAllBytes(jStrings[0]); }
public async Task <string> CreateProject() { var groupShareClient = Helper.GsClient; var projectRequest = new ProjectsRequest("/", true, 7) { Filter = { ProjectName = "today" } }; var result = await groupShareClient.Project.GetProject(projectRequest); if (result.Items.Count == 0) { var rawData = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Grammar.zip")); var projectName = $"Project - {Guid.NewGuid()}"; var projectId = await groupShareClient.Project.CreateProject(new CreateProjectRequest( projectName, Helper.OrganizationId, null, DateTime.Now.AddDays(2), ProjectTemplateId, rawData)); Assert.True(!string.IsNullOrEmpty(projectId)); return(projectId); } return(null); }
public IActionResult LoadMusic(int Id) { using (var db = new Context()) { var track = db.Track.Include(x => x.SingerTrack) .ThenInclude(x => x.Singer) .Include(x => x.GenreTrack) .ThenInclude(x => x.Genre) .FirstOrDefault(x => x.ID == Id); if (track == null) { var ex = new Exception($"Track is not found by ID = {Id}"); _logger.LogWarning(ex, "", null); throw ex; } if (string.IsNullOrEmpty(track.Path)) { var ex = new Exception($"Track path is empty by ID = {Id}"); _logger.LogWarning(ex, "", null); throw ex; } var buf = FileIO.ReadAllBytes(Path.Combine(musicDir, track.Path)); var webPath1 = Path.Combine("audio", $"{track.ID}{Path.GetExtension(track.Path)}"); var webPath2 = Path.Combine("..\\..\\..\\", "audio", $"{track.ID}{Path.GetExtension(track.Path)}"); var path = Path.Combine(_env.WebRootPath, webPath1); FileIO.WriteAllBytes(path, buf); //special path for web //webPath = @"" + webPath.Replace("/", @""); return(Json(webPath2)); } }
static string RunPack(bool fullstore) { var packList = new[] { "search.pack", // mem sig "network.pack", // net opcode $"dictionary.pack", // ui strings $"iconstore{(fullstore ? "" : $"_delta_{DateTime.Now:yyyyMMdd}")}.pack", // icon pack "apidef.pack" // api status }; var delta = $"mil{(fullstore ? "init" : "upd")}_{DateTime.Now:yyyyMMdd}.pack"; using (var deltaStm = new FileStream(delta, FileMode.Create)) using (var deltaArc = new ZipArchive(deltaStm, ZipArchiveMode.Create)) { foreach (var item in packList) { var ent = deltaArc.CreateEntry(item); using (var stm = ent.Open()) { var buf = File.ReadAllBytes(Helper.GetMilFilePathRaw(item)); stm.Write(buf, 0, buf.Length); } } } return(fullstore ? delta : null); }
public byte[] DownloadPepRequisitionFile(string chainId, string iin, string shepFileId = null) { if ("ShepFileID".Equals(shepFileId, StringComparison.OrdinalIgnoreCase)) { return(null); } var url = CommonConstants.PepRequisitionFileUrl.Replace("[url]", _configuration.ServerPepIp); var request = WebRequest.Create(string.Format(url, chainId, iin)); request.Method = "GET"; request.Timeout = ConfigShepUploader.TimoutMinutes * 60 * 1000; var dateTime = DateTime.Now; var localFilename = dateTime.ToString("yyyy-MM-dd ") + "at " + dateTime.ToString("HH-mm-ss-fff "); localFilename += "@ " + chainId + ".pdf"; localFilename = Path.Combine(_configuration.FolderRequisitionFile, localFilename); using (var response = request.GetResponse()) { using (var answerStream = response.GetResponseStream()) { using (var fileStream = new FileStream( localFilename, FileMode.CreateNew, FileAccess.Write)) { CopyStream(answerStream, fileStream); } } } return(File.ReadAllBytes(localFilename)); }
/// <summary> /// Parses each of the images in the document and posts them to the server. /// Updates the HTML with the returned Image Urls /// </summary> /// <param name="html">HTML that contains images</param> /// <param name="filename">image file name</param> /// <param name="wrapper">blog wrapper instance that sends</param> /// <param name="metaData">metadata containing post info</param> /// <returns>update HTML string for the document with updated images</returns> private string SendImages(string html, string filename, MetaWeblogWrapper wrapper, WeblogPostMetadata metaData) { var basePath = Path.GetDirectoryName(filename); var baseName = Path.GetFileName(basePath); var doc = new HtmlDocument(); doc.LoadHtml(html); try { // send up normalized path images as separate media items var images = doc.DocumentNode.SelectNodes("//img"); if (images != null) { foreach (HtmlNode img in images) { string imgFile = img.Attributes["src"]?.Value as string; if (imgFile == null) { continue; } if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://")) { imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\")); if (File.Exists(imgFile)) { var media = new MediaObject() { Type = "application/image", Bits = File.ReadAllBytes(imgFile), Name = baseName + "/" + Path.GetFileName(imgFile) }; var mediaResult = wrapper.NewMediaObject(media); img.Attributes["src"].Value = mediaResult.URL; // use first image as featured image if (string.IsNullOrEmpty(metaData.FeaturedImageUrl)) { metaData.FeaturedImageUrl = mediaResult.URL; } } } } html = doc.DocumentNode.OuterHtml; } } catch (Exception ex) { MessageBox.Show("Error posting images to Weblog: " + ex.Message, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation); mmApp.Log(ex); return(null); } return(html); }
private void btnAddFile_Click(object sender, EventArgs e) { try { using (var dialog = new OpenFileDialog()) { if (dialog.ShowDialog() == DialogResult.OK) { var fileContent = File.ReadAllBytes(dialog.FileName); var file = new Model.File { Name = Path.GetFileName(dialog.FileName), Owner = new User { Id = _userId } }; var fileId = _client.CreateFile(file); _client.UploadFileContent(fileId, fileContent); RefreshFileList(); MessageBox.Show($"Файл {file.Name} успешно загружен", "Загрузка файла", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception exception) { MessageBox.Show($"Не удалось загрузить файл, текст ошибки: {Environment.NewLine}{exception.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// todo : Remove unsed method public static byte[] To_PDF(string pdfPath, string barCodeImagePath) { var pdfWithAttachmentBytes = new byte[] { }; var pathToSavePDf = AppDomain.CurrentDomain.BaseDirectory + "Document\\PDFBarCodeAttached.pdf"; using (Stream inputPdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream inputImageStream = new FileStream(barCodeImagePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream outputPdfStream = new FileStream(pathToSavePDf, FileMode.Create, FileAccess.Write, FileShare.None)) { var reader = new PdfReader(inputPdfStream); var stamper = new PdfStamper(reader, outputPdfStream); var pdfContentByte = stamper.GetOverContent(1); var jpg = Image.GetInstance(inputImageStream); jpg.ScaleToFit(140f, 120f); jpg.SpacingBefore = 10f; jpg.SpacingAfter = 1f; jpg.Alignment = Element.ALIGN_LEFT; jpg.SetAbsolutePosition(100, 100); pdfContentByte.AddImage(jpg); stamper.Close(); pdfWithAttachmentBytes = File.ReadAllBytes(pathToSavePDf); } return(pdfWithAttachmentBytes); }
/// <summary> /// Actually uploads the package to the library /// Starting point: http://blog.symprogress.com/2013/07/upload-wsp-file-to-office365-sp2013-using-webclient/ /// </summary> /// <param name="siteUrl"></param> /// <param name="fileUrl"></param> /// <param name="localPath"></param> private void UploadFileToSharePointOnline(string siteUrl, string fileUrl, string localPath) { var targetSite = new Uri(siteUrl); using (var spWebClient = new SPWebClient()) { Console.WriteLine("Uploading package {0} to library ", Path.GetFileName(localPath)); var authCookie = ((SharePointOnlineCredentials)_credentials).GetAuthenticationCookie(targetSite); spWebClient.CookieContainer = new CookieContainer(); spWebClient.CookieContainer.Add(new Cookie("FedAuth", authCookie.Replace("SPOIDCRL=", string.Empty), string.Empty, targetSite.Authority)); spWebClient.UseDefaultCredentials = false; try { Stream stream = spWebClient.OpenWrite(fileUrl, "PUT"); var writer = new BinaryWriter(stream); writer.Write(File.ReadAllBytes(localPath)); writer.Close(); stream.Close(); Console.WriteLine("Uploaded package {0} to library ", Path.GetFileName(localPath)); } catch (WebException we) { Console.WriteLine(we.Message); } } }
void OnValidate() { if (!import) { return; } import = false; var liveRemotePath = RemotePath + @"\lives\" + liveName; var liveLocalPath = LocalPath + @"\lives\" + liveName + ".json"; string liveJson = File.ReadAllText(liveRemotePath); Debug.Log(liveJson); File.WriteAllText(liveLocalPath, liveJson); var live = JsonUtility.FromJson <ApiLiveResponse>(liveJson).content; Debug.Log(live.live_name); var mapRemotePath = RemotePath + @"\maps\" + live.map_path; var mapLocalPath = LocalPath + @"\maps\" + live.map_path; string mapJson = ApiLiveMap.Transform(File.ReadAllText(mapRemotePath)); File.WriteAllText(mapLocalPath, mapJson); var bgmRemotePath = RemotePath + @"\bgms\" + live.bgm_path; var bgmLocalPath = LocalPath + @"\bgms\" + live.bgm_path; byte[] bgmBytes = File.ReadAllBytes(bgmRemotePath); File.WriteAllBytes(bgmLocalPath, bgmBytes); }
private string VersionFile(string path) { if (path == null) { throw new ArgumentException($"{nameof(path)} may not be null."); } var pdbPath = Path.ChangeExtension(path, "pdb"); var versionedPath = GetNewPluginPath(path); Directory.CreateDirectory(Path.GetDirectoryName(versionedPath)); Debug.Assert(versionedPath != null, $"{nameof(versionedPath)} != null"); File.Copy(path, versionedPath, true); if (File.Exists(pdbPath)) { var versionedPdbPath = Path.ChangeExtension(versionedPath, "pdb"); File.Copy(pdbPath, versionedPdbPath, true); versionedPdbPath = Path.GetFileName(versionedPdbPath); // Do not include full path when patching dll // Update .pdb path in a newly copied file var pathBytes = Encoding.ASCII.GetBytes(Path.GetFileName(pdbPath)); // Does this work with i18n paths? var dllBytes = File.ReadAllBytes(versionedPath); int i; for (i = 0; i < dllBytes.Length; i++) { if (dllBytes.Skip(i).Take(pathBytes.Length).SequenceEqual(pathBytes)) // I know its slow ¯\_(ツ)_/¯ { if (dllBytes[i + pathBytes.Length] != 0) // Check for null terminator { continue; } while (dllBytes[--i] != 0) { // We found just a file name. Time to walk back to find a start of the string. This is // required because dll is executing from non-original directory and pdb path points // somewhere else we can not predict. } i++; // Copy full pdb path var newPathBytes = Encoding.ASCII.GetBytes(versionedPdbPath); newPathBytes.CopyTo(dllBytes, i); dllBytes[i + newPathBytes.Length] = 0; break; } } if (i == dllBytes.Length) { return(null); } File.WriteAllBytes(versionedPath, dllBytes); } return(versionedPath); }
public IActionResult DownloadFile([FromRoute] string id, [FromRoute] string filename) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else if (!lectureExists(id)) { return(NotFound(id)); } var file = _context.GetFullTable <Lecture>().Single(li => li.ID == id) .StorageItems?.SingleOrDefault(lsi => lsi.Filename == filename); if (file == null) { return(NotFound(filename)); } else { var filePath = Path.Combine(_storagePath, file.LectureRef.ID, file.Filename); if (!IOF.Exists(filePath)) { return(NotFound("File does not exist on server!")); } else { return(File(IOF.ReadAllBytes(filePath), "application/octet-stream")); } } }
/// <summary> /// Выгрузка и удаление файла докладной записки ЮЛ /// </summary> /// <returns></returns> public Stream FileArray() { var file = File.ReadAllBytes(FullPathDocumentWord); File.Delete(FullPathDocumentWord); return(new MemoryStream(file)); }
public async Task <string> CreateProject() { var groupShareClient = await Helper.GetGroupShareClient(); var projectRequest = new ProjectsRequest("/", true, 7) { Filter = { ProjectName = "today" } }; var result = await groupShareClient.Project.GetProject(projectRequest); if (result.Items.Count == 0) { var rawData = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\Grammar.zip")); var projectName = Guid.NewGuid().ToString(); var projectId = await groupShareClient.Project.CreateProject(new CreateProjectRequest( projectName, "ee72759d-917e-4c60-ba30-1ed595699c4d", null, DateTime.Now.AddDays(2), "7bf6410d-58a7-4817-a559-7aa8a3a99aa9", rawData)); Assert.True(!string.IsNullOrEmpty(projectId)); return(projectId); } return(null); }
private async Task <(RedirectedPackage, CompileResult)> Compile(Package package, Workspace workspace, string requestId) { var packageWithChanges = await CreatePackageWithChanges(package, workspace); try { await package.FullBuild(); // ensure `package.EntryPointAssemblyPath.FullName` has a value await packageWithChanges.FullBuild(); // copy the entire output directory back await CopyDirectory( Path.GetDirectoryName(packageWithChanges.EntryPointAssemblyPath.FullName), Path.GetDirectoryName(package.EntryPointAssemblyPath.FullName)); return(packageWithChanges, new CompileResult( true, // succeeded Convert.ToBase64String(File.ReadAllBytes(package.EntryPointAssemblyPath.FullName)), diagnostics: null, requestId: requestId)); } catch (Exception e) { packageWithChanges.Clean(); return(null, new CompileResult( false, // succeeded string.Empty, // assembly base64 new SerializableDiagnostic[] { // TODO: populate with real compiler diagnostics new SerializableDiagnostic(0, 0, e.Message, DiagnosticSeverity.Error, "Compile error") }, requestId)); } }
public void ProcessFile(string path, string password, long totalSize) { var webPath = Settings.Get("WebServer").WebFilePath.ToString(); var tempFolderPath = webPath + "temp\\"; if (!Directory.Exists(tempFolderPath)) { Directory.CreateDirectory(tempFolderPath); } var file = new FileInfo(path); file.Directory?.Create(); // If the directory already exists, this method does nothing. var fileName = Path.GetFileName(path); var ip = NetworkService.GetIPv4Address(); var port = (int)Settings.Get("WebServer").WebServerPort; var data = File.ReadAllBytes(path); var encryptedFile = _builder.PackFile(password, data); try { if (encryptedFile != null) { var tempPath = Path.Combine(tempFolderPath, fileName); File.WriteAllBytes(tempPath, encryptedFile); var tempWebPath = $"http://{ip}:{port}/temp/{fileName}"; var downloadData = new { tempWebPath, totalSize }; _builder.WriteMessage(downloadData); } else { var errorData = new { error = true, message = "Unable to encrypt file" }; _builder.WriteMessage(errorData); } } catch ( Exception e) { var exceptionData = new { error = true, message = e.Message }; _builder.WriteMessage(exceptionData); } }
private void tsbImport_Click(object sender, EventArgs e) { if (_fs == null) { return; } var ofd = new OpenFileDialog(); ofd.Title = "Import..."; if (_lastImportExportPath != null) { ofd.InitialDirectory = _lastImportExportPath; } ofd.CheckFileExists = true; ofd.CheckPathExists = true; ofd.Multiselect = true; if (ofd.ShowDialog() == DialogResult.OK) { _lastImportExportPath = IODirectory.GetParent(ofd.FileName).FullName; List <string> _invalidFiles = new List <string>(); using (new WaitCursor(this)) { for (var i = 0; i < ofd.FileNames.Length; i++) { var safename = Path.GetFileName(ofd.FileNames[i]); File file = FindFileByName(safename); if (file == null) { _invalidFiles.Add(safename); } else { byte[] data = IOFile.ReadAllBytes(ofd.FileNames[i]); file.SetData(data); } } } if (_invalidFiles.Count > 0) { var sb = new StringBuilder(); foreach (var s in _invalidFiles) { sb.Append(" " + s + "\n"); } MessageBox.Show("The following files were not found in the archive to be replaced:\n\n" + sb + "\nPlease note that you can not add new files, only replace existing ones. The files must be named exactly " + "as they are in the archive.", "Import", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } PopulateListView(); } }
[HttpGet("{id}")] //Get request public IActionResult GetImage(int id) //IActionResult converts data to json { var webRoot = _env.WebRootPath; //navigating to wwwroot folder var path = Path.Combine($"{webRoot}/Pics/", $"Event{id}.jpg"); //navigating to the picture var buffer = IOFile.ReadAllBytes(path); return(File(buffer, "image/jpeg")); }
/// <summary> /// Reads the entire contents of a file. /// </summary> /// <param name="path">The path of the file.</param> /// <returns> /// The contents of a file, in binary. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public byte[] ReadAllBytes(string path) { _ = Requires.NotNullOrWhiteSpace( path, nameof(path)); return(FSFile.ReadAllBytes(path)); }
public static byte[] GetFile(string path, bool isBinary, string baseFilePath) { if (!baseFilePath.EndsWith(@"\")) { baseFilePath = baseFilePath + @"\"; } return(File.ReadAllBytes(baseFilePath + path)); }
public IActionResult GetImage(int id) { var webRoot = _env.WebRootPath; var path = Path.Combine($"{webRoot}/pics/", $"Pic{id}.jpg"); var buffer = IOFile.ReadAllBytes(path); return(File(buffer, "image/jpeg")); }
private static CreateTicketModel GetTicketModel(string projectName) { Console.Write("Enter ticket title: "); string ticketTitle = Console.ReadLine(); Console.WriteLine("Ticket Types:"); Console.WriteLine("0 - Bug report"); Console.WriteLine("1 - Feature request"); Console.WriteLine("2 - Assistace request"); Console.WriteLine("3 - Other"); Console.Write("Enter ticket type: "); string ticketType = Console.ReadLine(); Console.WriteLine("Ticket States:"); Console.WriteLine("0 - New"); Console.WriteLine("1 - Draft"); Console.WriteLine("2 - Worked on"); Console.WriteLine("3 - Done"); Console.Write("Enter ticket state: "); string ticketState = Console.ReadLine(); Console.WriteLine("Enter description: "); string ticketDescription = Console.ReadLine(); Console.WriteLine("Enter file path(optional): "); string filePath = Console.ReadLine(); Project project = _projectService.GetByName(projectName); if (!string.IsNullOrEmpty(filePath)) { byte[] file = File.ReadAllBytes(filePath); string fileName = Path.GetFileName(filePath); return(new CreateTicketModel() { TicketTitle = ticketTitle, TicketType = ticketType, TicketState = ticketState, TicketDescription = ticketDescription, FileContent = file, FileName = fileName, ProjectId = project.Id, SubmitterId = _identity.UserId }); } return(new CreateTicketModel() { TicketTitle = ticketTitle, TicketType = ticketType, TicketState = ticketState, TicketDescription = ticketDescription, ProjectId = project.Id, SubmitterId = _identity.UserId }); }
public static void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { args.TokenCache.Deserialize(File.Exists(CacheFilePath) ? File.ReadAllBytes(CacheFilePath) : null); } }