• How to download the file in C#
    protected IActionResult Download(string filePath) { var memory = new MemoryStream(); using (var stream = new FileStream(filePath, FileMode.Open)) { stream.CopyTo(memory); } memory.Position = 0; Response.Headers.Add("X-FileName", Path.GetFileName(filePath)); Response.Headers.Add("Access-Control-Expose-Headers", "Access-Control-Expose-Headers:X-FileName"); return File(memory, GetContentType(filePath), Path.GetFileName(filePath)); } protected string GetContentType(string path) { var types = GetMimeTypes(); var ext = Path.GetExtension(path).ToLowerInvariant(); if (types.ContainsKey(ext)) return types[ext]; return "application/octet-stream"; } private Dictionary<string, string> … Read more
  • How to save the file in C#
    var filePath = Path.Combine(folderPath, fileName); using (var stream = new FileStream(filePath, FileMode.OpenOrCreate)) { FormFile.CopyTo(stream); }
  • How to extract .zip file in C#
    If you have .zip file and you want to extract it, Just pass folder path where it should be extracted ZipFile.ExtractToDirectory(zipFilePathWhereItIsStored, folderPathWhereFilesWillExtraxt, Encoding.UTF8, true);
  • How to read .txt file in C#
    Below code will return the text of a file var text = new StringBuilder(); var stream = new FileStream(path, FileMode.OpenOrCreate); using (var reader = new StreamReader(stream)) { while (reader.Peek() >= 0) text.AppendLine(reader.ReadLine()); } text.ToString();
  • How to read .pdf file in C# as a string
    public string ConvertPdfFileInToText(string path) { var stream = new FileStream(path, FileMode.OpenOrCreate); using (PdfReader reader = new PdfReader(stream)) { StringBuilder text = new StringBuilder(); for (int i = 1; i <= reader.NumberOfPages; i++) { text.Append(PdfTextExtractor.GetTextFromPage(reader, i)); } return text.ToString(); } }

Leave a Reply

Your email address will not be published. Required fields are marked *