Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c# - How to convert a file into byte array in memory?

Here is my code:

 public async Task<IActionResult> Index(ICollection<IFormFile> files)
 {
    foreach (var file in files)
        uploaddb(file);   

    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            await file.SaveAsAsync(Path.Combine(uploads, fileName));
        }
    }
}

Now I am converting this file into byte array using this code:

var filepath = Path.Combine(_environment.WebRootPath, "uploads/Book1.xlsx");
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
string s = Convert.ToBase64String(fileBytes);

And then I am uploading this code into my nosql database.This is all working fine but the problem is i don't want to save the file. Instead of that i want to directly upload the file into my database. And it can be possible if i can just convert the file into byte array directly without saving it.

public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
    foreach (var file in files)
        uploaddb(file);   
    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

///Code to Convert the file into byte array
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As opposed to saving the data as a string (which allocates more memory than needed and might not work if the binary data has null bytes in it), I would recommend an approach more like

foreach (var file in files)
{
  if (file.Length > 0)
  {
    using (var ms = new MemoryStream())
    {
      file.CopyTo(ms);
      var fileBytes = ms.ToArray();
      string s = Convert.ToBase64String(fileBytes);
      // act on the Base64 data
    }
  }
}

Also, for the benefit of others, the source code for IFormFile can be found on GitHub


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...