Click here to Skip to main content
16,020,347 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can I encode string in c#?

i add using system.web
and my code is:
C#
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);



or
System.Web.HttpUtility.HtmlEncode
but i can't use this
Posted
Comments
OriginalGriff 11-Mar-13 4:07am    
Why not? What problem are you having?
e.v.r 11-Mar-13 4:09am    
i have error for example this:
Error 2 The name 'HtmlEncode' does not exist in the current context
Prasad Khandekar 11-Mar-13 4:40am    
Hello,

If you are using .NET Framework 4 then you should be using System.Net.WebUtility.HtmLEncode.
e.v.r 11-Mar-13 4:54am    
Hello,
yes, I use .net framework 4, but there isn't in my VS.
for example my error is htmlencode or webutility is not in my VS
Prasad Khandekar 11-Mar-13 5:54am    
Your code will have a import clause as using System.Net. HttoUtility is a class located in this namespace for dotnet version 4 & 4.5.

If  you can't use HtmlEncode then you can use Base64Encode Method<br />

Like.
C#
Encode


public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}
Decode


public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Ref.
http://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string[^]
 
Share this answer
 
 
Share this answer
 
System.Web.HttpUtility.HtmlEncode("YOUR TEXT")
 
Share this answer
 
Server.HtmlEncode is a old method typically used in old ASP pages. You shoud use System.Net.WebUtility.HtmlEncode, it is supported in 4 & 4.5. For older versions use System.Web.HttpServerUtility.HtmlEncode.

Regards,
 
Share this answer
 
v3
Comments
e.v.r 11-Mar-13 4:20am    
this name space is not in my vs.
this error is :
Error 1 The type or namespace name 'HttpUtility' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
Aarti Meswania 11-Mar-13 4:58am    
add reference System.Net/System.Web
e.v.r 11-Mar-13 6:34am    
Thank you
Aarti Meswania 11-Mar-13 6:36am    
welcome! :)
TheRealSteveJudge 17-Feb-15 3:07am    
5*

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900