Here are the examples of the csharp api System.Text.Encoding.GetEncoding(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1077 Examples
19
View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private Dictionary<string,string> BuildForm(HttpListenerContext ctx)
{
string[] items;
string post;
using (StreamReader sr = new StreamReader(ctx.Request.InputStream))
{
post = sr.ReadToEnd();
}
if (string.IsNullOrEmpty(post))
return null;
items = post.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
var dict = new Dictionary<string, string>();
foreach (var item in items)
{
string[] kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (kv.Length == 2)
{
kv[1] = System.Web.HttpUtility.UrlDecode(kv[1],Encoding.GetEncoding("iso-8859-9"));
dict.Add(kv[0], kv[1]);
}
}
return dict;
}
19
View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private string NormalizeValue(string value)
{
value = value.Replace("$lt;", "<").
Replace("$gt;", ">").Replace("$amp;", "&").Replace("$eq;", "=")
.Replace("$percnt;", "%");
value = System.Web.HttpUtility.UrlDecode(value, Encoding.GetEncoding("ISO-8859-9"));
value = System.Web.HttpUtility.HtmlDecode(value).Replace("$plus;","+");
return value;
}
19
View Source File : Helper.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public static string NormalizeTurkishChars(string text)
{
byte[] tempBytes;
tempBytes = Encoding.GetEncoding("ISO-8859-8").GetBytes(text);
return Encoding.UTF8.GetString(tempBytes);
}
19
View Source File : ConnectionStringBuilder.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static ConnectionStringBuilder Parse(string connectionString)
{
var ret = new ConnectionStringBuilder();
if (string.IsNullOrEmpty(connectionString)) return ret;
//支持密码中带有逗号,将原有 split(',') 改成以下处理方式
var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
ret.Host = vs[0].Trim();
for (var a = 1; a < vs.Length; a += 2)
{
var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
switch (kv[0])
{
case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
case "userid":
case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
case "database":
case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;
case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
case "name":
case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;
case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;
case "poolsize":
case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
}
}
return ret;
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1");
});
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.domain_01 API V1");
});
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
app.UseDeveloperExceptionPage();
app.UseImServer(new ImServerOptions
{
Redis = new FreeRedis.RedisClient(Configuration["ImServerOption:RedisClient"]),
Servers = Configuration["ImServerOption:Servers"].Split(";"),
Server = Configuration["ImServerOption:Server"]
});
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Configure(IApplicationBuilder app)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.GetEncoding("GB2312");
Console.InputEncoding = Encoding.GetEncoding("GB2312");
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseEndpoints(config => config.MapControllers());
app.UseDefaultFiles();
app.UseStaticFiles();
ImHelper.Initialization(new ImClientOptions
{
Redis = new FreeRedis.RedisClient("127.0.0.1:6379,poolsize=10"),
Servers = new[] { "127.0.0.1:6001" }
});
ImHelper.Instance.OnSend += (s, e) =>
Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");
ImHelper.EventBus(
t =>
{
Console.WriteLine(t.clientId + "上线了");
var onlineUids = ImHelper.GetClientListByOnline();
ImHelper.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
},
t => Console.WriteLine(t.clientId + "下线了"));
}
19
View Source File : Util.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static string GetString(byte[] b, string encoding = QQGlobal.QQCharsetDefault)
{
try
{
return Encoding.GetEncoding(encoding).GetString(b);
}
catch
{
return Encoding.Default.GetString(b);
}
}
19
View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
{
cookieContainer = cookieContainer ?? new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = cookieContainer;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static string Get(string Url, string gettDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool GetHash(string m_strSource, ref byte[] HashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
Buffer = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
return true;
}
19
View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
{
//是否返回Byte类型数据
if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
//从这里开始我们要无视编码了
if (encoding == null)
{
Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
string c = string.Empty;
if (meta != null && meta.Groups.Count > 0)
{
c = meta.Groups[1].Value.ToLower().Trim();
}
if (c.Length > 2)
{
try
{
encoding = Encoding.GetEncoding(c.Replace("\"", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
}
catch
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
else
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool GetHash(string m_strSource, ref string strHashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
byte[] HashData;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
Buffer = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
strHashData = Convert.ToBase64String(HashData);
return true;
}
19
View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063
License : MIT License
Project Creator : a2633063
private bool SendStr(String str, bool hexbool)
{
byte[] sendData = null;
if (hexbool)
{
try
{
sendData = strToHexByte(str.Trim());
}
catch (Exception)
{
//throw;
MessageBox.Show("字符串转十六进制有误,请检测输入格式.", "错误!");
return false;
}
}
else if (rbtnSendASCII.Checked)
{
//sendData = Encoding.ASCII.GetBytes(str);
sendData = Encoding.GetEncoding("GBK").GetBytes(str);
}
else if (rbtnSendUTF8.Checked)
{
sendData = Encoding.UTF8.GetBytes(str);
}
else if (rbtnSendUnicode.Checked)
{
sendData = Encoding.Unicode.GetBytes(str);
}
else
{
sendData = Encoding.GetEncoding("GBK").GetBytes(str);
}
if (this.SendData(sendData))//发送数据成功计数
{
lblSendCount.Invoke(new MethodInvoker(delegate
{
lblSendCount.Text = "发送:" + (int.Parse(lblSendCount.Text.Substring(3)) + sendData.Length).ToString();
}));
return true;
}
return false;
}
19
View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063
License : MIT License
Project Creator : a2633063
public void AddData(byte[] data)
{
if (rbtnHex.Checked)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.AppendFormat("{0:x2}" + " ", data[i]);
}
AddContent(sb.ToString().ToUpper());
}
else if (rbtnUTF8.Checked)
{
AddContent(new UTF8Encoding().GetString(data));
}
else if (rbtnUnicode.Checked)
{
AddContent(new UnicodeEncoding().GetString(data));
}
else// if (rbtnASCII.Checked)
{
//AddContent(new ASCIIEncoding().GetString(data));
AddContent(Encoding.GetEncoding("GBK").GetString(data));
}
lblRevCount.Invoke(new MethodInvoker(delegate
{
lblRevCount.Text = "接收:" + (int.Parse(lblRevCount.Text.Substring(3)) + data.Length).ToString();
}));
}
19
View Source File : Rest.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static string GetBasicAuthentication(string username, string preplacedword)
{
return $"Basic {Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{preplacedword}"))}";
}
19
View Source File : APIConsumerHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
private static string ReadResponseStream(Stream receiveStream)
{
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, encode);
Char[] read = new Char[256];
// Reads 256 characters at a time.
int count = readStream.Read(read, 0, 256);
var strP = "";
while (count > 0)
{
// Dumps the 256 characters on a string and displays the string to the console.
String str = new String(read, 0, count);
Console.Write(str);
strP += str;
count = readStream.Read(read, 0, 256);
}
return strP;
}
19
View Source File : POParser.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public static Encoding DetectEncoding(Stream stream)
{
var reader = new StreamReader(stream, Encoding.GetEncoding("ASCII"), detectEncodingFromByteOrderMarks: true);
var parser = new POParser(new POParserSettings { ReadHeaderOnly = true, ReadContentTypeHeaderOnly = true });
POParseResult result = parser.Parse(reader);
if (!result.Success)
return null;
return
result.Catalog.Encoding != null ?
Encoding.GetEncoding(result.Catalog.Encoding) :
reader.CurrentEncoding;
}
19
View Source File : IdeaForumDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetDefaultIdeaPartialUrl(string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return replacedleSlug;
}
19
View Source File : IssueForumDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetDefaultIssuePartialUrl(string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return replacedleSlug;
}
19
View Source File : CmsEntityServiceProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string GetDefaultBlogPostPartialUrl(DateTime date, string replacedle)
{
if (string.IsNullOrWhiteSpace(replacedle))
{
throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
}
string replacedleSlug;
try
{
// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
// the Cyrillic code page is available.
replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
}
catch
{
replacedleSlug = replacedle.ToLowerInvariant();
}
// Strip all disallowed characters.
replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);
// Convert all runs of multiple spaces to a single space.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();
// Cap the length of the replacedle slug.
replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();
// Replace all spaces with hyphens.
replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');
return "{0:yyyy}-{0:MM}-{0:dd}-{1}".FormatWith(date, replacedleSlug);
}
19
View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
static Encoding Get_Encoding(Encode _Encode)
{
switch (_Encode)
{
case Encode.UTF7: return Encoding.UTF7;
case Encode.UTF32: return Encoding.UTF32;
case Encode.UNICODE: return Encoding.Unicode;
case Encode.ASCII: return Encoding.ASCII;
case Encode.GB2312:
return Encoding.GetEncoding("GB2312");
case Encode.GBK:
return Encoding.GetEncoding("GBK");
default: return Encoding.UTF8;
}
}
19
View Source File : StringExtend.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private static string GetPinyinChar(char c)
{
string str = c.ToString();
if ((int)c >= 32 && (int)c <= 126)
{
return str;
}
byte[] array = new byte[2];
Encoding gbEncoding;
try
{
gbEncoding = System.Text.Encoding.GetEncoding("GB2312");
}
catch
{
throw new Exception("GB2312 Text Encoding is not registered, please register it on app start ");
}
array = gbEncoding.GetBytes(str);
int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
if (i < 0xB0A1) return "#";
if (i < 0xB0C5) return "A";
if (i < 0xB2C1) return "B";
if (i < 0xB4EE) return "C";
if (i < 0xB6EA) return "D";
if (i < 0xB7A2) return "E";
if (i < 0xB8C1) return "F";
if (i < 0xB9FE) return "G";
if (i < 0xBBF7) return "H";
if (i < 0xBFA6) return "J";
if (i < 0xC0AC) return "K";
if (i < 0xC2E8) return "L";
if (i < 0xC4C3) return "M";
if (i < 0xC5B6) return "N";
if (i < 0xC5BE) return "O";
if (i < 0xC6DA) return "P";
if (i < 0xC8BB) return "Q";
if (i < 0xC8F6) return "R";
if (i < 0xCBFA) return "S";
if (i < 0xCDDA) return "T";
if (i < 0xCEF4) return "W";
if (i < 0xD1B9) return "X";
if (i < 0xD4D1) return "Y";
if (i < 0xD7FA) return "Z";
return "#";
}
19
View Source File : RSACryption.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool GetHash(string m_strSource, ref byte[] HashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
Buffer = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
return true;
}
19
View Source File : RSACryption.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool GetHash(string m_strSource, ref string strHashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
byte[] HashData;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
Buffer = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
strHashData = Convert.ToBase64String(HashData);
return true;
}
19
View Source File : UrlHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string MyUrlDeCode(string str, Encoding encoding)
{
if (encoding != null)
return HttpUtility.UrlDecode(str, encoding);
//首先用utf-8进行解码
var code = HttpUtility.UrlDecode(str.ToUpper(), Encoding.UTF8);
//将已经解码的字符再次进行编码.
var encode = HttpUtility.UrlEncode(code, Encoding.UTF8)?.ToUpper();
encoding = str == encode ? Encoding.UTF8 : Encoding.GetEncoding("gb2312");
return HttpUtility.UrlDecode(str, encoding);
}
19
View Source File : UrlHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string MyUrlDeCode(string str, Encoding encoding)
{
if (encoding != null)
return HttpUtility.UrlDecode(str, encoding);
var utf8 = Encoding.UTF8;
//首先用utf-8进行解码
var code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
//将已经解码的字符再次进行编码.
var encode = HttpUtility.UrlEncode(code, utf8)?.ToUpper();
encoding = str == encode ? Encoding.UTF8 : Encoding.GetEncoding("gb2312");
return HttpUtility.UrlDecode(str, encoding);
}
19
View Source File : UrlHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string MyUrlDeCode(string str, Encoding encoding)
{
if (encoding == null)
{
Encoding utf8 = Encoding.UTF8;
//首先用utf-8进行解码
string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
//将已经解码的字符再次进行编码.
string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
if (str == encode)
encoding = Encoding.UTF8;
else
encoding = Encoding.GetEncoding("gb2312");
}
return HttpUtility.UrlDecode(str, encoding);
}
19
View Source File : Elf.cs
License : The Unlicense
Project Creator : AigioL
License : The Unlicense
Project Creator : AigioL
private void _readLE()
{
_entries = new List<string>();
{
var i = 0;
while (!m_io.IsEof)
{
_entries.Add(System.Text.Encoding.GetEncoding("ASCII").GetString(m_io.ReadBytesTerm(0, false, true, true)));
i++;
}
}
}
19
View Source File : Elf.cs
License : The Unlicense
Project Creator : AigioL
License : The Unlicense
Project Creator : AigioL
private void _readBE()
{
_entries = new List<string>();
{
var i = 0;
while (!m_io.IsEof)
{
_entries.Add(System.Text.Encoding.GetEncoding("ASCII").GetString(m_io.ReadBytesTerm(0, false, true, true)));
i++;
}
}
}
19
View Source File : BasicAuthFilter.cs
License : MIT License
Project Creator : alanedwardes
License : MIT License
Project Creator : alanedwardes
private (string Username, string Preplacedword) GetCredentials(IHeaderDictionary headers)
{
if (!headers.ContainsKey(AuthorizationHeader))
{
throw new InvalidOperationException("No Authorization header found.");
}
string[] authValues = headers[AuthorizationHeader].ToArray();
if (authValues.Length != 1)
{
throw new InvalidOperationException("More than one Authorization header found.");
}
string auth = authValues.Single();
if (!auth.StartsWith(BasicPrefix))
{
throw new InvalidOperationException("Authorization header is not Basic.");
}
auth = auth.Substring(BasicPrefix.Length).Trim();
byte[] decoded = Convert.FromBase64String(auth);
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
string[] authPair = iso.GetString(decoded).Split(':');
return (authPair[0], authPair[1]);
}
19
View Source File : EncodedJsonFileTest.cs
License : MIT License
Project Creator : AlexTeixeira
License : MIT License
Project Creator : AlexTeixeira
[TestMethod]
public void TestReadName1_ISOEncoding()
{
CultureInfo.CurrentUICulture = new CultureInfo("fr-FR");
JsonLocalizer.Localizer.JsonStringLocalizer localizer = JsonStringLocalizerHelperFactory.Create(new JsonLocalizationOptions()
{
DefaultCulture = new CultureInfo("en-US"),
SupportedCultureInfos = new System.Collections.Generic.HashSet<CultureInfo>()
{
new CultureInfo("fr-FR")
},
ResourcesPath = "encoding",
FileEncoding = Encoding.GetEncoding("ISO-8859-1")
});
LocalizedString result = localizer.GetString("Name1");
replacedert.AreEqual("Mon Nom 1", result);
}
19
View Source File : EncodedJsonFileTest.cs
License : MIT License
Project Creator : AlexTeixeira
License : MIT License
Project Creator : AlexTeixeira
[TestMethod]
public void TestReadName1_ISOEncoding_SpecialChar()
{
CultureInfo.CurrentUICulture = new CultureInfo("pt-PT");
JsonLocalizer.Localizer.JsonStringLocalizer localizer = JsonStringLocalizerHelperFactory.Create(new JsonLocalizationOptions()
{
DefaultCulture = new CultureInfo("en-US"),
SupportedCultureInfos = new System.Collections.Generic.HashSet<CultureInfo>()
{
new CultureInfo("fr-FR"),
new CultureInfo("pt-PT")
},
ResourcesPath = "encoding",
FileEncoding = Encoding.GetEncoding("ISO-8859-1")
});
LocalizedString result = localizer.GetString("Name1");
replacedert.AreEqual("Eu so joão", result);
}
19
View Source File : AopXmlParser.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public T Parse(string body, string charset)
{
XmlSerializer serializer = null;
string rootTagName = GetRootElement(body);
bool inc = parsers.TryGetValue(rootTagName, out serializer);
if (!inc || serializer == null)
{
XmlAttributes rootAttrs = new XmlAttributes();
rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName);
XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
attrOvrs.Add(typeof(T), rootAttrs);
serializer = new XmlSerializer(typeof(T), attrOvrs);
parsers[rootTagName] = serializer;
}
object obj = null;
Encoding encoding = null;
if (string.IsNullOrEmpty(charset))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(charset);
}
using (Stream stream = new MemoryStream(encoding.GetBytes(body)))
{
obj = serializer.Deserialize(stream);
}
T rsp = (T)obj;
if (rsp != null)
{
rsp.Body = body;
}
return rsp;
}
19
View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override bool DoVerify(string content, string charset, string publicKey, string sign)
{
using (RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider())
{
rsaService.PersistKeyInCsp = false;
rsaService.ImportParameters(ConvertFromPemPublicKey(publicKey));
return rsaService.VerifyData(Encoding.GetEncoding(charset).GetBytes(content),
GetShaType(), Convert.FromBase64String(sign));
}
}
19
View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public string DoPost(string url, IDictionary<string, string> parameters, string charset)
{
HttpWebRequest req = GetWebRequest(url, "POST");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
byte[] postData = Encoding.GetEncoding(charset).GetBytes(BuildQuery(parameters, charset));
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public string DoGet(string url, IDictionary<string, string> parameters, string charset)
{
if (parameters != null && parameters.Count > 0)
{
if (url.Contains("?"))
{
url = url + "&" + BuildQuery(parameters, charset);
}
else
{
url = url + "?" + BuildQuery(parameters, charset);
}
}
HttpWebRequest req = GetWebRequest(url, "GET");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public string DoPost(string url, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams, string charset)
{
// 如果没有文件参数,则走普通POST请求
if (fileParams == null || fileParams.Count == 0)
{
return DoPost(url, textParams, charset);
}
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
HttpWebRequest req = GetWebRequest(url, "POST");
req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;
Stream reqStream = req.GetRequestStream();
byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");
// 组装文本请求参数
string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
while (textEnum.MoveNext())
{
string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
}
// 组装文件请求参数
string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
while (fileEnum.MoveNext())
{
string key = fileEnum.Current.Key;
FileItem fileItem = fileEnum.Current.Value;
string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(fileEntry);
reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
reqStream.Write(itemBytes, 0, itemBytes.Length);
byte[] fileBytes = fileItem.GetContent();
reqStream.Write(fileBytes, 0, fileBytes.Length);
}
reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponsereplacedtring(rsp, encoding);
}
19
View Source File : WebUtils.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public static string BuildQuery(IDictionary<string, string> parameters, string charset)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));
postData.Append(encodedValue);
hasParam = true;
}
}
return postData.ToString();
}
19
View Source File : AlipayMobilePublicMultiMediaClient.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
private AopResponse DoGet(AopDictionary parameters, Stream outStream)
{
AlipayMobilePublicMultiMediaDownloadResponse response = null;
string url = this.serverUrl;
System.Console.WriteLine(url);
if (parameters != null && parameters.Count > 0)
{
if (url.Contains("?"))
{
url = url + "&" + WebUtils.BuildQuery(parameters, charset);
}
else
{
url = url + "?" + WebUtils.BuildQuery(parameters, charset);
}
}
HttpWebRequest req = webUtils.GetWebRequest(url, "GET");
req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
if (rsp.ContentType.ToLower().Contains("text/plain"))
{
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
string body = webUtils.GetResponsereplacedtring(rsp, encoding);
IAopParser<AlipayMobilePublicMultiMediaDownloadResponse> tp = new AopJsonParser<AlipayMobilePublicMultiMediaDownloadResponse>();
response = tp.Parse(body, charset);
}
else
{
GetResponsereplacedtream(outStream, rsp);
response = new AlipayMobilePublicMultiMediaDownloadResponse();
}
}
return response;
}
19
View Source File : SM2Encryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoDecrypt(string cipherTextBase64, string charset, string privateKey)
{
//加载私钥参数
ICipherParameters cipherParams = BuildPrivateKeyParams(privateKey).Parameters;
//初始化SM2算法引擎
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, cipherParams);
//对输入密文进行解密
byte[] input = Convert.FromBase64String(cipherTextBase64);
byte[] output = sm2Engine.ProcessBlock(input, 0, input.Length);
//将解密后的明文按指定字符集编码后返回
return Encoding.GetEncoding(charset).GetString(output);
}
19
View Source File : SM2Encryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoEncrypt(string plainText, string charset, string publicKey)
{
//加载公钥参数
ICipherParameters cipherParams = BuildPublickKeyParams(publicKey).Parameters;
ParametersWithRandom parametersWithRandom = new ParametersWithRandom(cipherParams);
//初始化SM2算法引擎
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, parametersWithRandom);
//对输入明文进行加密
byte[] input = Encoding.GetEncoding(charset).GetBytes(plainText);
byte[] output = sm2Engine.ProcessBlock(input, 0, input.Length);
//将密文Base64编码后返回
return Convert.ToBase64String(output);
}
19
View Source File : SM2Encryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoSign(string content, string charset, string privateKey)
{
//加载私钥参数
ParametersWithID parametersWithID = BuildPrivateKeyParams(privateKey);
//加载签名器
SM2Signer signer = new SM2Signer();
signer.Init(true, parametersWithID);
//向签名器中输入原文
byte[] input = Encoding.GetEncoding(charset).GetBytes(content);
signer.BlockUpdate(input, 0, input.Length);
//将签名结果转换为Base64
return Convert.ToBase64String(signer.GenerateSignature());
}
19
View Source File : SM2Encryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override bool DoVerify(string content, string charset, string publicKey, string sign)
{
//加载公钥参数
ParametersWithID parametersWithID = BuildPublickKeyParams(publicKey);
//加载签名器
SM2Signer signer = new SM2Signer();
signer.Init(false, parametersWithID);
//向签名器中输入原文
byte[] input = Encoding.GetEncoding(charset).GetBytes(content);
signer.BlockUpdate(input, 0, input.Length);
//传入指定签名串进行验签并返回结果
return signer.VerifySignature(Convert.FromBase64String(sign));
}
19
View Source File : AlipayEncrypt.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public static string AesEncrypt(string encryptKey, string bizContent, string charset)
{
Byte[] keyArray = Convert.FromBase64String(encryptKey);
byte[] toEncryptArray;
if (string.IsNullOrEmpty(charset))
{
toEncryptArray = Encoding.UTF8.GetBytes(bizContent);
}
else
{
toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent);
}
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
rDel.IV = AES_IV;
ICryptoTransform cTransform = rDel.CreateEncryptor(rDel.Key, rDel.IV);
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray);
}
19
View Source File : AlipayEncrypt.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public static string AesDencrypt(string encryptKey, string bizContent, string charset)
{
Byte[] keyArray = Convert.FromBase64String(encryptKey);
Byte[] toEncryptArray = Convert.FromBase64String(bizContent);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
rDel.IV = AES_IV;
ICryptoTransform cTransform = rDel.CreateDecryptor(rDel.Key, rDel.IV);
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
if (string.IsNullOrEmpty(charset))
{
return Encoding.UTF8.GetString(resultArray);
}
else
{
return Encoding.GetEncoding(charset).GetString(resultArray);
}
}
19
View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoDecrypt(string cipherTextBase64, string charset, string privateKey)
{
using (RSACryptoServiceProvider rsaService = BuildRSAServiceProvider(Convert.FromBase64String(privateKey)))
{
byte[] data = Convert.FromBase64String(cipherTextBase64);
//解密块最大长度
int maxBlockSize = rsaService.KeySize / 8;
//如果密文长度小于等于单个解密块最大长度,直接单次调用解密接口完成解密
if (data.Length <= maxBlockSize)
{
byte[] cipherbytes = rsaService.Decrypt(data, false);
return Encoding.GetEncoding(charset).GetString(cipherbytes);
}
//如果密文长度大于单个解密块最大长度,在内存中循环调用解密接口完成解密
using (MemoryStream plainStream = new MemoryStream())
{
using (MemoryStream cipherStream = new MemoryStream(data))
{
Byte[] buffer = new Byte[maxBlockSize];
int readSize = cipherStream.Read(buffer, 0, maxBlockSize);
while (readSize > 0)
{
Byte[] cipherBlock = new Byte[readSize];
Array.Copy(buffer, 0, cipherBlock, 0, readSize);
Byte[] plainBlock = rsaService.Decrypt(cipherBlock, false);
plainStream.Write(plainBlock, 0, plainBlock.Length);
readSize = cipherStream.Read(buffer, 0, maxBlockSize);
}
}
return Encoding.GetEncoding(charset).GetString(plainStream.ToArray());
}
}
}
19
View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoEncrypt(string plainText, string charset, string publicKey)
{
using (RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider())
{
rsaService.PersistKeyInCsp = false;
rsaService.ImportParameters(ConvertFromPemPublicKey(publicKey));
byte[] data = Encoding.GetEncoding(charset).GetBytes(plainText);
//加密块最大长度
int maxBlockSize = rsaService.KeySize / 8 - 11;
//如果明文长度小于等于单个加密块最大长度,直接单次调用加密接口完成加密
if (data.Length <= maxBlockSize)
{
byte[] cipherbytes = rsaService.Encrypt(data, false);
return Convert.ToBase64String(cipherbytes);
}
//如果明文长度大于单个加密块最大长度,在内存中循环调用加密接口完成加密
using (MemoryStream cipherStream = new MemoryStream())
{
using (MemoryStream plainStream = new MemoryStream(data))
{
Byte[] buffer = new Byte[maxBlockSize];
int readSize = plainStream.Read(buffer, 0, maxBlockSize);
while (readSize > 0)
{
Byte[] plainBlock = new Byte[readSize];
Array.Copy(buffer, 0, plainBlock, 0, readSize);
Byte[] cipherBlock = rsaService.Encrypt(plainBlock, false);
cipherStream.Write(cipherBlock, 0, cipherBlock.Length);
readSize = plainStream.Read(buffer, 0, maxBlockSize);
}
}
return Convert.ToBase64String(cipherStream.ToArray(), Base64FormattingOptions.None);
}
}
}
19
View Source File : RSAEncryptor.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
protected override string DoSign(string content, string charset, string privateKey)
{
using (RSACryptoServiceProvider rsaService = BuildRSAServiceProvider(Convert.FromBase64String(privateKey)))
{
byte[] data = Encoding.GetEncoding(charset).GetBytes(content);
byte[] sign = rsaService.SignData(data, GetShaType());
return Convert.ToBase64String(sign);
}
}
See More Examples