Shishank Jain
Shishank Jain

Reputation: 11

How to encode a csv file to UTF-8 using C# and asp.net core?

I have a csv file which contains latin characters (Ascii value > 127). The file gets uploaded with any type of encoding and shows the right data after uploading. But it gets converted automatically to UTF8 after performing operations on the file.

But I am not able to see the same characters when it is converted to UTF8 after performing operations.

I believe if I will upload the files with UTF8 encoding only then I will see the same characters that were present while uploading the file. So I want to encode the file with UTF8 Encoding.

I am getting IForm File from the function. I tried these methods to change the encoding but it does not affect the file in any way.

First method

//'file' is the IForm file 
string[] filecontent;

StreamReader sr = new StreamReader(file.FileName);
string data = sr.ReadLine();
filecontent = data.Split(",");
File.WriteAllLines(file.FileName, filecontent, Encoding.UTF8);

Second method

var fileStream2 = File.OpenWrite(file.FileName);
var sw = new StreamWriter(fileStream2, Encoding.UTF8, 1024, false);
sw.Write(fileStream2);
sw.Close();

Is there any other method to do this or is there any other library to encode the csv file with UTF 8 directly?

Upvotes: 0

Views: 2138

Answers (0)

Related Questions