Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write special character (é, è) with StreamWriter?

My problem : I want to write datas with a StreamWriter (my String contains letters é and è) but it doesn't work. Without this letters, it works.

The error : Cannot close the stream

My code :

 string postString = "id=" + sIdTransaction + "&nom=" + sNom + "&prenom=" + sPrenom + "&email=" + sEmail + "&adresse.rue=" + sRue + "&adresse.codePostal=" + sCodePostal + "&adresse.ville=" + sVille;
string sIdContractant = "";
Encoding iso = Encoding.GetEncoding("utf-8");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(postString);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
postString = iso.GetString(isoBytes);

string sUrlAuth = "https://test.contralia.fr/Contralia/api/transactions/" + sIdTransaction + "/contractant/";
HttpWebRequest webRequest = CreationRequete(sUrlAuth);
webRequest.ContentLength = postString.Length;


StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();


adresse.Ville = Fercé (problem with this é)

How can I resolve this problem please ?
Thanks

like image 435
user2471450 Avatar asked Jul 24 '13 11:07

user2471450


2 Answers

Set the encoding for the StreamWriter:

StreamWriter sw = new StreamWriter(webRequest.GetRequestStream(), encoding)

Try this, I hope it helps. It worked for me!

like image 64
butterbox Avatar answered Oct 06 '22 17:10

butterbox


Replace your code by this :

string postString = "id=" + sIdTransaction + "&nom=" + sNom + "&prenom=" + sPrenom + "&email=" + sEmail + "&adresse.rue=" + sRue + "&adresse.codePostal=" + sCodePostal + "&adresse.ville=" + sVille;
string sIdContractant = "";
Encoding iso = Encoding.GetEncoding("utf-8");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(postString);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
postString = iso.GetString(isoBytes);

string sUrlAuth = "https://test.contralia.fr/Contralia/api/transactions/" + sIdTransaction + "/contractant/";
HttpWebRequest webRequest = CreationRequete(sUrlAuth);
webRequest.ContentLength = postString.Length;


StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream(), iso);
requestWriter.Write(postString);
requestWriter.Close();

i just changer, in your 11th line, StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
by
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream(), iso);

like image 34
Thomas BLANCHET Avatar answered Oct 06 '22 19:10

Thomas BLANCHET