Here are the examples of the csharp api System.Text.Encoding.GetString(byte[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
6169 Examples
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 : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static async Task Step18ExportToJson(ISqDatabase database)
{
var tableUser = new TableUser(Alias.Empty);
var selectExpr = Select(tableUser.FirstName, tableUser.LastName)
.From(tableUser)
.Where(tableUser.LastName == "Sturman")
.Done();
//Exporting
var memoryStream = new MemoryStream();
var jsonWriter = new Utf8JsonWriter(memoryStream);
selectExpr.SyntaxTree().ExportToJson(jsonWriter);
string json = Encoding.UTF8.GetString(memoryStream.ToArray());
Console.WriteLine(json);
//Importing
var restored = (ExprQuerySpecification)ExprDeserializer
.DeserializeFormJson(JsonDoreplacedent.Parse(json).RootElement);
var result = await restored
.QueryList(database, r => (tableUser.FirstName.Read(r), tableUser.LastName.Read(r)));
foreach (var name in result)
{
Console.WriteLine(name);
}
}
19
View Source File : Chromium.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
public static string Decrypt(string encryptedData)
{
if (encryptedData == null || encryptedData.Length == 0)
return null;
try
{
return Encoding.UTF8.GetString(ProtectedData.Unprotect(Encoding.Default.GetBytes(encryptedData), null, DataProtectionScope.CurrentUser));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private string GetValueStringFromOffset()
{
string valueString;
TagDataType type = this.entry.Type;
uint count = this.entry.Count;
uint offset = this.entry.Offset;
if (count == 0)
{
return string.Empty;
}
int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);
if (typeSizeInBytes == 1)
{
byte[] bytes = new byte[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
if (type == TagDataType.Ascii)
{
valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
}
else if (count == 1)
{
valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
}
else
{
StringBuilder builder = new StringBuilder();
uint lasreplacedemIndex = count - 1;
for (int i = 0; i < count; i++)
{
builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));
if (i < lasreplacedemIndex)
{
builder.Append(",");
}
}
valueString = builder.ToString();
}
}
else if (typeSizeInBytes == 2)
{
ushort[] values = new ushort[count];
if (this.offsetIsBigEndian)
{
switch (count)
{
case 1:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
values[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
values[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
values[0] = (ushort)(offset & 0x0000ffff);
values[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
if (count == 1)
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture);
break;
}
}
else
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
((short)values[1]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
values[1].ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
valueString = offset.ToString(CultureInfo.InvariantCulture);
}
return valueString;
}
19
View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private static List<string> DecodeMessageBuffer(byte[] bytes)
{
const byte Separator = (byte)'\n';
int startOffset = 0;
int count = 0;
List<string> messageParameters = new List<string>();
if (bytes[bytes.Length - 1] == Separator)
{
// A message with multiple values uses \n as the separator and terminator.
for (int i = 0; i < bytes.Length; i++)
{
if (bytes[i] == Separator)
{
// Empty strings are skipped.
if (count > 0)
{
messageParameters.Add(Encoding.UTF8.GetString(bytes, startOffset, count));
}
startOffset = i + 1;
count = 0;
}
else
{
count++;
}
}
}
else
{
messageParameters.Add(Encoding.UTF8.GetString(bytes));
}
return messageParameters;
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private string GetValueStringFromOffset()
{
string valueString;
TagDataType type = entry.Type;
uint count = entry.Count;
uint offset = entry.Offset;
if (count == 0)
{
return string.Empty;
}
int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);
if (typeSizeInBytes == 1)
{
byte[] bytes = new byte[count];
if (offsetIsBigEndian)
{
switch (count)
{
case 1:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
break;
case 2:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)((offset >> 24) & 0x000000ff);
bytes[1] = (byte)((offset >> 16) & 0x000000ff);
bytes[2] = (byte)((offset >> 8) & 0x000000ff);
bytes[3] = (byte)(offset & 0x000000ff);
break;
}
}
else
{
switch (count)
{
case 1:
bytes[0] = (byte)(offset & 0x000000ff);
break;
case 2:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
break;
case 3:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
break;
case 4:
bytes[0] = (byte)(offset & 0x000000ff);
bytes[1] = (byte)((offset >> 8) & 0x000000ff);
bytes[2] = (byte)((offset >> 16) & 0x000000ff);
bytes[3] = (byte)((offset >> 24) & 0x000000ff);
break;
}
}
if (type == TagDataType.Ascii)
{
valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
}
else if (count == 1)
{
valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
}
else
{
StringBuilder builder = new StringBuilder();
uint lasreplacedemIndex = count - 1;
for (int i = 0; i < count; i++)
{
builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));
if (i < lasreplacedemIndex)
{
builder.Append(",");
}
}
valueString = builder.ToString();
}
}
else if (typeSizeInBytes == 2)
{
ushort[] values = new ushort[count];
if (offsetIsBigEndian)
{
switch (count)
{
case 1:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
break;
case 2:
values[0] = (ushort)((offset >> 16) & 0x0000ffff);
values[1] = (ushort)(offset & 0x0000ffff);
break;
}
}
else
{
switch (count)
{
case 1:
values[0] = (ushort)(offset & 0x0000ffff);
break;
case 2:
values[0] = (ushort)(offset & 0x0000ffff);
values[1] = (ushort)((offset >> 16) & 0x0000ffff);
break;
}
}
if (count == 1)
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture);
break;
}
}
else
{
switch (type)
{
case TagDataType.SShort:
valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
((short)values[1]).ToString(CultureInfo.InvariantCulture);
break;
case TagDataType.Short:
default:
valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
values[1].ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
valueString = offset.ToString(CultureInfo.InvariantCulture);
}
return valueString;
}
19
View Source File : IrdParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static Ird Parse(byte[] content)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
if (content.Length < 200)
throw new ArgumentException("Data is too small to be a valid IRD structure", nameof(content));
if (BitConverter.ToInt32(content, 0) != Ird.Magic)
using (var compressedStream = new MemoryStream(content, false))
using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var decompressedStream = new MemoryStream())
{
gzip.CopyTo(decompressedStream);
content = decompressedStream.ToArray();
}
if (BitConverter.ToInt32(content, 0) != Ird.Magic)
throw new FormatException("Not a valid IRD file");
var result = new Ird();
using (var stream = new MemoryStream(content, false))
using (var reader = new BinaryReader(stream, Encoding.UTF8))
{
reader.ReadInt32(); // magic
result.Version = reader.ReadByte();
result.ProductCode = Encoding.ASCII.GetString(reader.ReadBytes(9));
result.replacedleLength = reader.ReadByte();
result.replacedle = Encoding.UTF8.GetString(reader.ReadBytes(result.replacedleLength));
result.UpdateVersion = Encoding.ASCII.GetString(reader.ReadBytes(4)).Trim();
result.GameVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
result.AppVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
if (result.Version == 7)
result.Id = reader.ReadInt32();
result.HeaderLength = reader.ReadInt32();
result.Header = reader.ReadBytes(result.HeaderLength);
result.FooterLength = reader.ReadInt32();
result.Footer = reader.ReadBytes(result.FooterLength);
result.RegionCount = reader.ReadByte();
result.RegionMd5Checksums = new List<byte[]>(result.RegionCount);
for (var i = 0; i < result.RegionCount; i++)
result.RegionMd5Checksums.Add(reader.ReadBytes(16));
result.FileCount = reader.ReadInt32();
result.Files = new List<IrdFile>(result.FileCount);
for (var i = 0; i < result.FileCount; i++)
{
var file = new IrdFile();
file.Offset = reader.ReadInt64();
file.Md5Checksum = reader.ReadBytes(16);
result.Files.Add(file);
}
result.Unknown = reader.ReadInt32();
if (result.Version == 9)
result.Pic = reader.ReadBytes(115);
result.Data1 = reader.ReadBytes(16);
result.Data2 = reader.ReadBytes(16);
if (result.Version < 9)
result.Pic = reader.ReadBytes(115);
result.Uid = reader.ReadInt32();
var dataLength = reader.BaseStream.Position;
result.Crc32 = reader.ReadUInt32();
var crc32 = Crc32Algorithm.Compute(content, 0, (int)dataLength);
if (result.Crc32 != crc32)
throw new InvalidDataException($"Corrupted IRD data, expected {result.Crc32:x8}, but was {crc32:x8}");
}
return result;
}
19
View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static string Hex2String(this string val)
{
if (val.IsNull())
return null;
var bytes = val.Hex2Bytes();
return Encoding.UTF8.GetString(bytes);
}
19
View Source File : NativeAPI.cs
License : Apache License 2.0
Project Creator : 1694439208
License : Apache License 2.0
Project Creator : 1694439208
public static string ReadMemoryStrValue(int baseAddress,int len)
{
try
{
byte[] buffer = new byte[len];
//获取缓冲区地址
IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
//打开一个已存在的进程对象 0x1F0FFF 最高权限
//IntPtr hProcess = OpenProcess(0x1F0FFF, false, GetPidByProcessName(""));
//将制定内存中的值读入缓冲区
ReadProcessMemory(-1, (IntPtr)baseAddress, byteAddress, len, IntPtr.Zero.ToInt32());
//关闭操作
//CloseHandle(hProcess);
//从非托管内存中读取一个 32 位带符号整数。
return Encoding.Unicode.GetString(buffer);
}
catch
{
return "";
}
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static string FromBase64(this string s)
{
byte[] data = Convert.FromBase64String(s);
return Encoding.UTF8.GetString(data);
}
19
View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
static string CreateScriptlet(string script, string script_name, bool register_script, Guid clsid)
{
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.LoadXml(Global_Var.scriptlet_template);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
settings.Encoding = new UTF8Encoding(false);
XmlElement reg_node = (XmlElement)doc.SelectSingleNode("/package/component/registration");
XmlNode root_node = register_script ? reg_node : doc.SelectSingleNode("/package/component");
XmlNode script_node = root_node.AppendChild(doc.CreateElement("script"));
script_node.Attributes.Append(doc.CreateAttribute("language")).Value = script_name;
script_node.AppendChild(doc.CreateCDataSection(script));
if (clsid != Guid.Empty)
{
reg_node.SetAttribute("clreplacedid", clsid.ToString("B"));
}
using (MemoryStream stm = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(stm, settings))
{
doc.Save(writer);
}
return Encoding.UTF8.GetString(stm.ToArray());
}
}
19
View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Decrypt(string key, string data)
{
Encoding unicode = Encoding.Unicode;
return unicode.GetString(Encrypt(unicode.GetBytes(key), Convert.FromBase64String(data)));
}
19
View Source File : CSRedisClientStringTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Append() {
var key = "TestAppend_null";
rds.Set(key, base.String);
rds.Append(key, base.Null);
replacedert.Equal(rds.Get(key), base.String);
key = "TestAppend_string";
rds.Set(key, base.String);
rds.Append(key, base.String);
replacedert.Equal(rds.Get(key), base.String + base.String);
var ms = new MemoryStream();
rds.Get(key, ms);
replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), base.String + base.String);
ms.Close();
key = "TestAppend_bytes";
rds.Set(key, base.Bytes);
rds.Append(key, base.Bytes);
replacedert.Equal(Convert.ToBase64String(rds.Get<byte[]>(key)), Convert.ToBase64String(base.Bytes.Concat(base.Bytes).ToArray()));
}
19
View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
19
View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Append()
{
var key = "TestAppend_null";
cli.Set(key, String);
cli.Append(key, Null);
replacedert.Equal(cli.Get(key), String);
key = "TestAppend_string";
cli.Set(key, String);
cli.Append(key, String);
replacedert.Equal(cli.Get(key), String + String);
var ms = new MemoryStream();
cli.Get(key, ms);
replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
ms.Close();
key = "TestAppend_bytes";
cli.Set(key, Bytes);
cli.Append(key, Bytes);
replacedert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
}
19
View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string ReadTextFile(string path) {
byte[] bytes = ReadFile(path);
return Encoding.UTF8.GetString(bytes).TrimStart((char)65279);
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async public static Task<string> GetBodyRawText(HttpRequest req) {
var charsetIndex = req.ContentType.IndexOf("charset=");
var charset = Encoding.UTF8;
if (charsetIndex != -1) {
var charsetText = req.ContentType.Substring(charsetIndex + 8);
charsetIndex = charsetText.IndexOf(';');
if (charsetIndex != -1) charsetText = charsetText.Remove(charsetIndex);
switch (charsetText.ToLower()) {
case "utf8":
case "utf-8":
break;
default:
charset = Encoding.GetEncoding(charsetText);
break;
}
}
req.Body.Position = 0;
using (var ms = new MemoryStream()) {
await req.Body.CopyToAsync(ms);
return charset.GetString(ms.ToArray());
}
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private static VmessItem ResolveSip002(string result)
{
Uri parsedUrl;
try
{
parsedUrl = new Uri(result);
}
catch (UriFormatException)
{
return null;
}
VmessItem server = new VmessItem
{
remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped),
address = parsedUrl.IdnHost,
port = parsedUrl.Port,
};
// parse base64 UserInfo
string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.Unescaped);
string base64 = rawUserInfo.Replace('-', '+').Replace('_', '/'); // Web-safe base64 to normal base64
string userInfo;
try
{
userInfo = Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=')));
}
catch (FormatException)
{
return null;
}
string[] userInfoParts = userInfo.Split(new char[] { ':' }, 2);
if (userInfoParts.Length != 2)
{
return null;
}
server.security = userInfoParts[0];
server.id = userInfoParts[1];
NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUrl.Query);
if (queryParameters["plugin"] != null)
{
return null;
}
return server;
}
19
View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private static VmessItem ResolveSSLegacy(string result)
{
var match = UrlFinder.Match(result);
if (!match.Success)
return null;
VmessItem server = new VmessItem();
var base64 = match.Groups["base64"].Value.TrimEnd('/');
var tag = match.Groups["tag"].Value;
if (!Utils.IsNullOrEmpty(tag))
{
server.remarks = Utils.UrlDecode(tag);
}
Match details;
try
{
details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));
}
catch (FormatException)
{
return null;
}
if (!details.Success)
return null;
server.security = details.Groups["method"].Value;
server.id = details.Groups["preplacedword"].Value;
server.address = details.Groups["hostname"].Value;
server.port = int.Parse(details.Groups["port"].Value);
return server;
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string Base64Decode(string plainText)
{
try
{
plainText = plainText.TrimEx()
.Replace(Environment.NewLine, "")
.Replace("\n", "")
.Replace("\r", "")
.Replace(" ", "");
if (plainText.Length % 4 > 0)
{
plainText = plainText.PadRight(plainText.Length + 4 - plainText.Length % 4, '=');
}
byte[] data = Convert.FromBase64String(plainText);
return Encoding.UTF8.GetString(data);
}
catch (Exception ex)
{
SaveLog("Base64Decode", ex);
return string.Empty;
}
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string UnGzip(byte[] buf)
{
MemoryStream sb = new MemoryStream();
using (GZipStream input = new GZipStream(new MemoryStream(buf),
CompressionMode.Decompress,
false))
{
input.CopyTo(sb);
}
return Encoding.UTF8.GetString(sb.ToArray());
}
19
View Source File : Slack.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public string SendNotification(string payload, string text)
{
var data = new NameValueCollection();
data["token"] = token;
data["channel"] = channel;
data["as_user"] = "true";
data["text"] = text;
data["attachments"] = payload;
var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
return JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(response))["ts"];
}
19
View Source File : Compression.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static string Unzip(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
19
View Source File : Slack.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public string EditNotification(string payload, string text, string ts)
{
var data = new NameValueCollection();
data["token"] = token;
data["channel"] = channel;
data["as_user"] = "true";
data["text"] = text;
data["ts"] = ts;
data["attachments"] = payload;
var response = client.UploadValues("https://slack.com/api/chat.update", "POST", data);
return JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(response))["ts"];
}
19
View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
public static void ReadWaveHeader(Stream stream, out WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<RiffChunk> chunks)
{
dataChunkPosition = -1;
format = null;
BinaryReader br = new BinaryReader(stream);
if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "RIFF")//WaveInterop.mmioStringToFOURCC("RIFF", 0)
{
throw new FormatException("Not a WAVE file - no RIFF header");
}
uint fileSize = br.ReadUInt32(); // read the file size (minus 8 bytes)
if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "WAVE")//WaveInterop.mmioStringToFOURCC("WAVE", 0)
{
throw new FormatException("Not a WAVE file - no WAVE header");
}
int dataChunkID = BitConverter.ToInt32(Encoding.UTF8.GetBytes("data"), 0); ;//WaveInterop.mmioStringToFOURCC("data", 0)
int formatChunkId = BitConverter.ToInt32(Encoding.UTF8.GetBytes("fmt "), 0); ;//WaveInterop.mmioStringToFOURCC("fmt ", 0)
dataChunkLength = 0;
// sometimes a file has more data than is specified after the RIFF header
long stopPosition = Math.Min(fileSize + 8, stream.Length);
// this -8 is so we can be sure that there are at least 8 bytes for a chunk id and length
while (stream.Position <= stopPosition - 8)
{
Int32 chunkIdentifier = br.ReadInt32();
Int32 chunkLength = br.ReadInt32();
if (chunkIdentifier == dataChunkID)
{
dataChunkPosition = stream.Position;
dataChunkLength = chunkLength;
stream.Position += chunkLength;
}
else if (chunkIdentifier == formatChunkId)
{
format = WaveFormat.FromFormatChunk(br, chunkLength);
}
else
{
// check for invalid chunk length
if (chunkLength < 0 || chunkLength > stream.Length - stream.Position)
{
Debug.replacedert(false, String.Format("Invalid chunk length {0}, pos: {1}. length: {2}",
chunkLength, stream.Position, stream.Length));
// an exception will be thrown further down if we haven't got a format and data chunk yet,
// otherwise we will tolerate this file despite it having corrupt data at the end
break;
}
if (chunks != null)
{
chunks.Add(new RiffChunk(chunkIdentifier, chunkLength, stream.Position));
}
stream.Position += chunkLength;
}
}
if (format == null)
{
throw new FormatException("Invalid WAV file - No fmt chunk found");
}
if (dataChunkPosition == -1)
{
throw new FormatException("Invalid WAV file - No data chunk found");
}
}
19
View Source File : ByteExpand.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static string GetString(this byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
19
View Source File : TLV_0108.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public void Parser_Tlv(QQUser user, BinaryReader buf)
{
var type = buf.BeReadUInt16(); //type
var length = buf.BeReadUInt16(); //length
WSubVer = buf.BeReadUInt16(); //wSubVer
if (WSubVer == 0x0001)
{
var len = buf.BeReadUInt16();
var buffer = buf.ReadBytes(len);
var bufAccountBasicInfo = new BinaryReader(new MemoryStream(buffer));
len = bufAccountBasicInfo.BeReadUInt16();
buffer = bufAccountBasicInfo.ReadBytes(len);
var info = new BinaryReader(new MemoryStream(buffer));
var wSsoAccountWFaceIndex = info.BeReadUInt16();
len = info.ReadByte();
if (len > 0)
{
user.NickName = Encoding.UTF8.GetString(info.ReadBytes(len));
}
user.Gender = info.ReadByte();
var dwSsoAccountDwUinFlag = info.BeReadUInt32();
user.Age = info.ReadByte();
var bufStOther =
bufAccountBasicInfo.ReadBytes(
(int) (bufAccountBasicInfo.BaseStream.Length - bufAccountBasicInfo.BaseStream.Position));
}
else
{
throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
}
}
19
View Source File : Richtext.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static Richtext Parse(BinaryReader reader)
{
var result = new Richtext();
// TODO: 解析富文本
try
{
var messageType = reader.ReadByte();
var dataLength = reader.BeReadUInt16();
var pos = reader.BaseStream.Position;
while (pos + dataLength < reader.BaseStream.Length)
{
reader.ReadByte();
switch (messageType)
{
case 0x01: // 纯文本消息、@
{
var messageStr = reader.BeReadString();
if (messageStr.StartsWith("@") && pos + dataLength - reader.BaseStream.Position == 16)
{
reader.ReadBytes(10);
result.Snippets.Add(new TextSnippet(messageStr, MessageType.At,
("Target", reader.BeReadLong32())));
}
else
{
result.Snippets.Add(messageStr);
}
break;
}
case 0x02: // Emoji(系统表情)
{
reader.BeReadUInt16(); // 这里的数字貌似总是1:系统表情只有208个。
result.Snippets.Add(new TextSnippet("", MessageType.Emoji, ("Type", reader.ReadByte())));
break;
}
case 0x03: // 图片
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Picture));
break;
}
case 0x0A: // 音频
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Audio));
break;
}
case 0x0E: // 未知
{
break;
}
case 0x12: // 群名片
{
break;
}
case 0x14: // XML
{
reader.ReadByte();
result.Snippets.Add(new TextSnippet(
GZipByteArray.DecompressString(reader.ReadBytes((int) (reader.BaseStream.Length - 1))),
MessageType.Xml));
break;
}
case 0x18: // 群文件
{
reader.ReadBytes(5);
var fileName = reader.BeReadString(); // 文件名称... 长度总是一个byte
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 文件大小
result.Snippets.Add(new TextSnippet(fileName, MessageType.OfflineFile));
break;
}
case 0x19: // 红包秘钥段
{
if (reader.ReadByte() != 0xC2)
{
break;
}
reader.ReadBytes(19);
reader.ReadBytes(reader.ReadByte()); // 恭喜发财
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 赶紧点击拆开吧
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // QQ红包
reader.ReadBytes(5);
reader.ReadBytes(reader.ReadByte()); // [QQ红包]恭喜发财
reader.ReadBytes(22);
var redId = Encoding.UTF8.GetString(reader.ReadBytes(32)); //redid
reader.ReadBytes(12);
reader.ReadBytes(reader.BeReadUInt16());
reader.ReadBytes(0x10);
var key1 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key1
reader.BeReadUInt16();
var key2 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key2
result.Snippets.Add(new TextSnippet("", MessageType.RedBag, ("RedId", redId),
("Key1", key1), ("Key2", key2)));
break;
}
}
reader.ReadBytes((int) (pos + dataLength - reader.BaseStream.Position));
messageType = reader.ReadByte();
dataLength = reader.BeReadUInt16();
pos = reader.BaseStream.Position;
}
}
catch (Exception ex)
{
}
// 移除所有空白的片段
result.Snippets.RemoveAll(s => s.Type == MessageType.Normal && string.IsNullOrEmpty(s.Content));
// 若长度大于1,那么应该只含有普通文本、At、表情、图片。
// 虽然我看着别人好像视频也能通过转发什么的弄进来,但是反正我们现在不支持接收音视频,所以不管了
return result.Snippets.Count > 1 && result.Snippets.Any(s =>
s.Type != MessageType.Normal && s.Type != MessageType.At &&
s.Type != MessageType.Emoji && s.Type != MessageType.Picture)
? throw new NotSupportedException("富文本中包含多个非聊天代码")
: result;
}
19
View Source File : Util.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static string ConvertHexToString(string hexValue)
{
var bytes = HexStringToByteArray(hexValue);
return Encoding.UTF8.GetString(bytes);
}
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 : Util.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static string BeReadString(this BinaryReader br, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
return encoding.GetString(br.ReadBytes(br.BeReadUInt16()));
}
19
View Source File : Converter.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
public static T FromBinary<T>(byte[] value)
{
string s = Encoding.UTF8.GetString(value);
return FromJson<T>(s);
}
19
View Source File : WebhookServerBase.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
private async Task Post(HttpRequest request, HttpResponse response, RouteData route)
{
var eventId = new EventId(EventId++);
try
{
byte[] bodyRaw = new byte[request.ContentLength.Value];
await request.Body.ReadAsync(bodyRaw, 0, bodyRaw.Length);
string body = Encoding.UTF8.GetString(bodyRaw);
if (PostReceived != null)
{
await Task.Run(() =>
{
PostReceived.Invoke(new WebhookEventArgs()
{
Request = request,
BodyRaw = bodyRaw,
Body = body,
Response = response
});
});
}
}
catch (Exception e)
{
Logger.LogError(eventId, e, e.Message);
}
}
19
View Source File : TLV_000A.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public void Parser_Tlv_0A(QQUser user, BinaryReader buf)
{
var type = buf.BeReadUInt16(); //type
var length = buf.BeReadUInt16(); //length
WSubVer = buf.BeReadUInt16(); //wSubVer
if (WSubVer == 0x0001)
{
var wCsCmd = buf.BeReadUInt16();
ErrorMsg = Encoding.UTF8.GetString(buf.ReadBytes(wCsCmd));
}
else
{
throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
}
}
19
View Source File : Send_0x0002.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public void HttpUpLoadGroupImg(long groupNum, string ukey, string fileName)
{
using (var webclient = new WebClient())
{
var file = new FileStream(fileName, FileMode.Open);
var apiUrl =
$"http://htdata2.qq.com/cgi-bin/httpconn?htcmd=0x6ff0071&ver=5515&term=pc&ukey={ukey}&filesize={file.Length}&range=0&uin{User.QQ}&&groupcode={groupNum}";
webclient.Headers["User-Agent"] = "QQClient";
webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var result = webclient.UploadData(apiUrl,
file.ToBytesArray());
Console.Write(Encoding.UTF8.GetString(result));
}
}
19
View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
private async Task Post(HttpRequest request, HttpResponse response, RouteData route)
{
var eventId = new EventId(_eventId++);
try
{
byte[] buf = new byte[request.ContentLength.Value];
await request.Body.ReadAsync(buf, 0, buf.Length);
string body = Encoding.UTF8.GetString(buf);
Logger.LogDebug(eventId, Resources.WebhookPost + body);
#if !DEBUG
const string signatureHeader = "X-Hub-Signature";
if (!request.Headers.Keys.Contains(signatureHeader))
{
Logger.LogWarning(Resources.InvalidSignature);
if (PostFailed != null)
{
ThreadPool.QueueUserWorkItem(state => PostFailed.Invoke(new PostEventArgs()
{
Headers = request.Headers,
Body = body
}));
}
return;
}
var signature = request.Headers[signatureHeader][0];
if (!VerifySignature(signature, buf))
{
Logger.LogWarning(Resources.InvalidSignature);
if (PostFailed != null)
{
ThreadPool.QueueUserWorkItem(state => PostFailed.Invoke(new PostEventArgs()
{
Headers = request.Headers,
Body = body
}));
}
return;
}
#endif
if (PostReceived != null)
{
ThreadPool.QueueUserWorkItem(state => PostReceived.Invoke(new PostEventArgs()
{
Headers = request.Headers,
Body = body
}));
}
ProcessRequest(body);
}
catch (Exception e)
{
Logger.LogError(eventId, e, e.Message);
}
}
19
View Source File : StringExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public static string ToDesDecrypt(this string text, string sKey = "[email protected]")
{
try
{
byte[] inputArray = Convert.FromBase64String(text);
var tripleDES = TripleDES.Create();
var byteKey = Encoding.UTF8.GetBytes(sKey);
tripleDES.Key = byteKey;
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
catch
{
return "";
}
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(m_strDecryptString);
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
{
byte[] DypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
DypherTextBArray = rsa.Decrypt(DecryptString, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act
License : MIT License
Project Creator : 91Act
public string ReadAlignedString(int length)
{
if (length > 0 && length < (BaseStream.Length - BaseStream.Position))
{
var stringData = ReadBytes(length);
var result = Encoding.UTF8.GetString(stringData);
AlignStream(4);
return result;
}
return "";
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act
License : MIT License
Project Creator : 91Act
public string ReadStringToNull()
{
var bytes = new List<byte>();
byte b;
while (BaseStream.Position != BaseStream.Length && (b = ReadByte()) != 0)
bytes.Add(b);
return Encoding.UTF8.GetString(bytes.ToArray());
}
19
View Source File : Base64.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
public static string DecodeBase64(Encoding encode, string result)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(result);
try
{
decode = encode.GetString(bytes);
}
catch
{
decode = result;
}
return decode;
}
19
View Source File : DCRadiumResponse.cs
License : MIT License
Project Creator : 99x
License : MIT License
Project Creator : 99x
public Task WriteAsync(byte[] data)
{
return this.res.WriteAsync(System.Text.Encoding.UTF8.GetString(data));
}
19
View Source File : DCRadiumResponse.cs
License : MIT License
Project Creator : 99x
License : MIT License
Project Creator : 99x
public Task WriteAsync(byte[] data, CancellationToken token)
{
return this.res.WriteAsync(System.Text.Encoding.UTF8.GetString(data), token);
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act
License : MIT License
Project Creator : 91Act
public string ReadASCII(int length)
{
return Encoding.ASCII.GetString(ReadBytes(length));
}
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 : TelloUdpClient.cs
License : MIT License
Project Creator : 8bitbytes
License : MIT License
Project Creator : 8bitbytes
public SdkWrapper.SdkReponses SendMessage(actions.Action action)
{
if(action.Type == actions.Action.ActionTypes.CommandMode && _commandMode)
{
return SdkWrapper.SdkReponses.OK;
}
if (_client == null)
{
return SdkWrapper.SdkReponses.FAIL;
}
_client.Connect(_endpoint);
var data = Encoding.ASCII.GetBytes(action.Command);
_client.Send(data, data.Length);
_client.Client.ReceiveTimeout = 2500;
var receiveBytes = _client.Receive(ref _remoteIpEndPoint);
_serverReponse = Encoding.ASCII.GetString(receiveBytes);
if(action.Type == actions.Action.ActionTypes.Read)
{
return _serverReponse == "FAIL" ? SdkWrapper.SdkReponses.FAIL
: SdkWrapper.SdkReponses.OK;
}
if(action.Type == actions.Action.ActionTypes.CommandMode && _serverReponse == "OK")
{
_commandMode = true;
}
return _serverReponse == "OK" ? SdkWrapper.SdkReponses.OK
: SdkWrapper.SdkReponses.FAIL;
}
19
View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
private void GetData(HttpItem item, HttpResult result)
{
if (response == null)
{
return;
}
#region base
//获取StatusCode
result.StatusCode = response.StatusCode;
//获取StatusDescription
result.StatusDescription = response.StatusDescription;
//获取Headers
result.Header = response.Headers;
//获取最后访问的URl
result.ResponseUri = response.ResponseUri.ToString();
//获取CookieCollection
if (response.Cookies != null) result.CookieCollection = response.Cookies;
//获取set-cookie
if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
#endregion base
#region byte
//处理网页Byte
byte[] ResponseByte = GetByte();
#endregion byte
#region Html
if (ResponseByte != null && ResponseByte.Length > 0)
{
//设置编码
SetEncoding(item, result, ResponseByte);
//得到返回的HTML
result.Html = encoding.GetString(ResponseByte);
}
else
{
//没有返回任何Html代码
result.Html = string.Empty;
}
#endregion Html
}
See More Examples