Read CSV File From Blazor Web Assembly

CSV is a very popular format and probably in somes scenarios we need to read this type of file to save information in the database or to do something else.
 
In this article, I will show you how to read this format (CSV) in Blazor web assembly applications
 
First, we need to add an InputFile element in the compenent where we want to read the file,
  1. <InputFile OnChange="@OnInputFileChange" class="btn btn-primary" />   
Then, we need to implement the event @OnInputFileChange where, we will validate the format and read the file's information, 
  1.   public async Task OnInputFileChange(InputFileChangeEventArgs e)  
  2.         {  
  3.             SpinnerModal.ShowSpinner();  
  4.             var singleFile = e.File;  
  5.   
  6.             Regex regex = new Regex(".+\\.csv", RegexOptions.Compiled);  
  7.             if (!regex.IsMatch(singleFile.Name))  
  8.             {  
  9.                 //show error invalidad format file  
  10.             }  
  11.             else  
  12.             {  
  13.                 var stream = singleFile.OpenReadStream();  
  14.                 var csv = new List<string[]>();  
  15.                 MemoryStream ms = new MemoryStream();  
  16.                 await stream.CopyToAsync(ms);  
  17.                 stream.Close();  
  18.                 var outputFileString = System.Text.Encoding.UTF8.GetString(ms.ToArray());  
  19.   
  20.                 foreach (var item in outputFileString.Split(Environment.NewLine))  
  21.                 {  
  22.                     csv.Add(SplitCSV(item.ToString()));  
  23.                 }  
  24.   
  25.              }  
  26.    }  
  27.   
  28.         private string[] SplitCSV(string input)  
  29.         {  
  30.             //Excludes commas within quotes  
  31.             Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);  
  32.             List<string> list = new List<string>();  
  33.             string curr = null;  
  34.             foreach (Match match in csvSplit.Matches(input))  
  35.             {  
  36.                 curr = match.Value;  
  37.                 if (0 == curr.Length)  list.Add(""); 
  38.   
  39.                 list.Add(curr.TrimStart(','));  
  40.             }  
  41.   
  42.             return list.ToArray();  
  43.         }  
SplitCSV reads the CSV file excluding the columns with commas in the values and also returns a string array including all the values.
 
At the end, we will have a csv array that includes the whole data and then, we can send that information to the server.
 
If you want to make a refactoring in this code feel fre to do it. Share your solution in the comment's section.


Similar Articles