How to convert httppostedfilebase to a String array

public ActionResult Import(HttpPostedFileBase currencyConversionsFile) { string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv"; string folderPath = Server.MapPath("~/Files/"); string filePath = Server.MapPath("~/Files/" + filename); currencyConversionsFile.SaveAs(filePath); string[] csvData = System.IO.File.ReadAllLines(filePath); //the later code isn't show here } 

I know the usual way to convert httppostedfilebase to a String array, which will first save the file to the server and then read the data from the server. Is there a way to get an array of strings directly from the httppostedfile database in order to save the file on the server?

+6
source share
2 answers

Well, you can read your file line by line from Stream as follows:

 List<string> csvData = new List<string>(); using (System.IO.StreamReader reader = new System.IO.StreamReader(currencyConversionsFile.InputStream)) { while (!reader.EndOfStream) { csvData.Add(reader.ReadLine()); } } 
+10
source

From another thread addressing the same problem, this answer helped me get the published file to a string -

fooobar.com/questions/130355 / ...

To quote

 string result = string.Empty; using (BinaryReader b = new BinaryReader(file.InputStream)) { byte[] binData = b.ReadBytes(file.ContentLength); result = System.Text.Encoding.UTF8.GetString(binData); } 

Splitting a string into an array -

 string[] csvData = new string[] { }; csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); 
+1
source

Source: https://habr.com/ru/post/984174/


All Articles