//External direction is encoder style. public Counter(EncodingType encodingType, DigitalSource upSource, DigitalSource downSource, bool inverted) { InitCounter(Mode.ExternalDirection); if (encodingType != EncodingType.K2X && encodingType != EncodingType.K1X) { throw new ArgumentOutOfRangeException(nameof(encodingType), "Counters only support 1X and 2X decoding!"); } if (upSource == null) throw new ArgumentNullException(nameof(upSource), "Up Source given was null"); if (downSource == null) throw new ArgumentNullException(nameof(downSource), "Down Source given was null"); SetUpSource(upSource); SetDownSource(downSource); int status = 0; if (encodingType == EncodingType.K1X) { SetUpSourceEdge(true, false); SetCounterAverageSize(m_counter, 1, ref status); } else { SetUpSourceEdge(true, true); SetCounterAverageSize(m_counter, 2, ref status); } CheckStatus(status); SetDownSourceEdge(inverted, true); }
public MediaFileInfo(MediaType mediaType, ContainerType containerType, EncodingType encondingType, String path) { mMediaType = mediaType; mContainerType = containerType; mEncondingType = encondingType; mPath = path; }
// Here we deserialize it back into its original form public static object DeserializeObject(string pXmlizedString, string rootElementName, Type ObjectType, EncodingType encodingType) { XmlRootAttribute xRoot = new XmlRootAttribute(); xRoot.ElementName = rootElementName; XmlSerializer xs = new XmlSerializer(ObjectType, xRoot); MemoryStream memoryStream = null; switch (encodingType) { case EncodingType.Unicode: memoryStream = new MemoryStream(StringToUTFUnicodeByteArray(pXmlizedString)); break; case EncodingType.UTF8: memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); break; case EncodingType.UTF7: break; default: memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); break; } return xs.Deserialize(memoryStream); }
/// <summary> /// Represents the HTML attribute "enctype". /// </summary> /// <param name="encodingType">The value.</param> /// <returns>The same instance of <see cref="Hex.AttributeBuilders.HtmlAttributeBuilder"/>.</returns> public HtmlAttributeBuilder EncType( EncodingType encodingType ) { string encodingTypeAttributeValue; switch( encodingType ) { case EncodingType.Multipart: { encodingTypeAttributeValue = ENCODING_TYPE_MULTIPART_FORM_DATA; break; } case EncodingType.Plain: { encodingTypeAttributeValue = ENCODING_TYPE_TEXT_PLAIN; break; } default: { encodingTypeAttributeValue = ENCODING_TYPE_APPLICATION_URL_ENCODED; break; } } this.Attributes[ HtmlAttributes.EncType ] = encodingTypeAttributeValue; return this; }
public Blob(string content, EncodingType encoding, string sha, int size) { Content = content; Encoding = encoding; Sha = sha; Size = size; }
protected EncodingProfile(EncodingType t, Encoding enc) { _type = t; _encoding = enc; _buffer = new byte[3]; //今は1文字は最大3バイト _cursor = 0; _tempOneCharArray = new char[1]; //APIの都合で長さ1のchar[]が必要なとき使う }
protected EncodingProfile(EncodingType t, Encoding enc) { _type = t; _encoding = enc; _buffer = new byte[3]; //���͂P�����͍ő�R�o�C�g _cursor = 0; }
static void Convert(string path, EncodingType to) { var binary = System.IO.File.ReadAllBytes(path); if (binary.Length < 3) return; EncodingType type = EncodingType.CP932; if ( binary[0] == 0xEF && binary[1] == 0xBB && binary[2] == 0xBF) { type = EncodingType.UTF8; } string text = null; if (type == EncodingType.UTF8) { text = System.IO.File.ReadAllText(path, Encoding.UTF8); } else if (type == EncodingType.CP932) { text = System.IO.File.ReadAllText(path, Encoding.GetEncoding(932)); } if (to == EncodingType.UTF8) { System.IO.File.WriteAllText(path, text, Encoding.UTF8); } else if(to == EncodingType.CP932) { System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(932)); } }
public void SetEncodingFilter(EncodingType encodingType, IEncoding encoding) { if (encodingType != null && encoding != null && !"*".Equals(encodingType.Name, StringComparison.Ordinal)) { this.OutputStream = encoding.Encode(encodingType, this.OutputStream); this.Headers["Content-Encoding"] = encodingType.Name; } }
protected EncodingProfile(EncodingType t, Encoding enc) { _type = t; _encoding = enc; _buffer = new byte[3]; //���͂P�����͍ő�R�o�C�g _cursor = 0; _tempOneCharArray = new char[1]; //API�̓s���Œ����P��char[]���K�v�ȂƂ��g�� }
public XmlActionResult(string xml, string fileName, EncodingType encoding = EncodingType.UTF8, LoadOptions loadOptions = System.Xml.Linq.LoadOptions.None) { XmlContent = xml; FileName = fileName; Encoding = encoding; LoadOptions = loadOptions; }
public FileStruct(string path, string name, string contentType, EncodingType type, byte[] data, FileInfo fileinfo) { Path = path; Name = name; ContentType = contentType; EncodingType = type; Data = data; FileInfo = fileinfo; }
protected Engine(MediaType mediaType, ContainerType inputFileContainerType, EncodingType inputFileEncondingType, String inputFilePath, String outputFilePath) : base(mediaType, inputFileContainerType, inputFileEncondingType, inputFilePath, outputFilePath) { if (!sInitialized) { // Native initialization here sInitialized = true; } }
/// <summary> /// Gets a value indicating whether this instance can encode the given <see cref="EncodingType"/>. /// </summary> /// <param name="encodingType">The <see cref="EncodingType"/> to encode.</param> /// <returns>True if this instance can encode the <see cref="EncodingType"/>, false otherwise.</returns> public bool CanEncode(EncodingType encodingType) { if (encodingType == null) { throw new ArgumentNullException("encodingType", "encodingType cannot be null."); } return encodingType.Accepts(GzipDeflateEncoding.Deflate) || encodingType.Accepts(GzipDeflateEncoding.Gzip); }
public static string Decrypt(this string identifier, Algorithm algorithm, string key, EncodingType encType) { Cypher cypher = new Cypher(); cypher.EncryptionAlgorithm = algorithm; cypher.Encoding = encType; if (key != null) cypher.Key = key; return cypher.Decrypt(identifier); }
public SimEncoder(int pin, EncodingType type = EncodingType.K4X) { if (type == EncodingType.K4X) { InitEncoder(pin); } else { InitCounter(pin); } }
public static Encoding GetEncoding(EncodingType encodingType) { switch (encodingType) { case EncodingType.ASCII: return Encoding.ASCII; case EncodingType.Unicode: return Encoding.Unicode; case EncodingType.UTF32: return Encoding.UTF32; case EncodingType.UTF7: return Encoding.UTF7; case EncodingType.UTF8: return Encoding.UTF8; default: return Encoding.Default; } }
/// <summary> /// Initializes a new instance of the <see cref="QRCodes"/> class. /// </summary> /// <param name="size">The chart size.</param> /// <param name="text">The text to encode.</param> /// <param name="encodingType">Type of the encoding.</param> public QRCodes(ChartSize size, string text, EncodingType encodingType) : base(QRCodeType, size) { _data = new PlainParam("chl", HttpUtility.UrlPathEncode(text)); // to reduce url length - do not add default encoding parameter if (DefaultEncoding != encodingType) { _encoding = new EncodingTypeParam(encodingType); } }
public EncoderTest(int inputA, int outputA, int inputB, int outputB, EncodingType type) { m_inputA = inputA; m_inputB = inputB; m_outputA = outputA; m_outputB = outputB; //If the encoder from a previous test is allocated then we must free its members s_encoder?.Teardown(); //this.flip = flip == 0; s_encoder = new FakeEncoderFixture(inputA, outputA, inputB, outputB, type); }
public void SetEncodingFilter(EncodingType encodingType, IEncoding encoding) { if (encodingType != null && encoding != null) { string contentEncoding = encoding.ContentEncoding(encodingType); if (!"*".Equals(contentEncoding, StringComparison.Ordinal)) { this.Headers["Content-Encoding"] = contentEncoding; this.httpResponse.Filter = encoding.Encode(encodingType, this.httpResponse.Filter); } } }
/// <summary> /// Creates a decoding stream around the given stream and returns /// the wrapped stream to use for decoding. /// </summary> /// <param name="encodingType">The <see cref="EncodingType"/> to decode.</param> /// <param name="stream">The stream to apply the decoding to.</param> /// <returns>A stream providing decoding services to the original stream.</returns> public Stream Decode(EncodingType encodingType, Stream stream) { if (encodingType == null) { throw new ArgumentNullException("encodingType", "encodingType cannot be null."); } if (stream == null) { throw new ArgumentNullException("stream", "stream cannot be null."); } return this.GetCompressionStream(encodingType, stream, CompressionMode.Decompress); }
public static IInStream Encode(this IInStream input, EncodingType encoding) { switch (encoding) { case EncodingType.Base64: return new Base64Encoder(input); case EncodingType.QuotedPrintable: return new QuotedPrintableEncoder(input); default: return input; } }
internal static Encoding CreateEncoder(EncodingType encoder) { switch (encoder) { case EncodingType.Utf8: return new UTF8Encoding(true, true); case EncodingType.Utf7: return new UTF7Encoding(false); case EncodingType.Ascii: return new ASCIIEncoding(); case EncodingType.Unicode: return new UnicodeEncoding(); case EncodingType.Ansi: return Encoding.Default; } throw (new NotImplementedException("The provided encoding is not avaiable")); }
public CompressedContent(HttpContent content, EncodingType encodingType) { if (content == null) { throw new ArgumentNullException("content"); } originalContent = content; this.encodingType = encodingType; // copy the headers from the original content foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers) { this.Headers.TryAddWithoutValidation(header.Key, header.Value); } this.Headers.ContentEncoding.Add(encodingType.ToString()); }
//Listener以外を持ってくる public virtual void Import(ITerminalSettings src) { _encoding = src.Encoding; _terminalType = src.TerminalType; _localecho = src.LocalEcho; _lineFeedRule = src.LineFeedRule; _transmitnl = src.TransmitNL; _caption = src.Caption; _icon = src.Icon; TerminalSettings src_r = (TerminalSettings)src; _shellSchemeName = src_r._shellSchemeName; //ちょっとインチキ if (src_r._shellScheme != null) { _shellScheme = src_r._shellScheme; TerminalEmulatorPlugin.Instance.ShellSchemeCollection.AddDynamicChangeListener(this); } _enabledCharTriggerIntelliSense = src.EnabledCharTriggerIntelliSense; _renderProfile = src.RenderProfile == null ? null : (RenderProfile)src.RenderProfile.Clone(); _multiLogSettings = src.LogSettings == null ? null : (IMultiLogSettings)_multiLogSettings.Clone(); }
public TerminalSettings() { IPoderosaCulture culture = TerminalEmulatorPlugin.Instance.PoderosaWorld.Culture; if (culture.IsJapaneseOS || culture.IsSimplifiedChineseOS || culture.IsTraditionalChineseOS || culture.IsKoreanOS) _encoding = EncodingType.UTF8; else _encoding = EncodingType.ISO8859_1; _terminalType = TerminalType.XTerm; _localecho = false; _lineFeedRule = LineFeedRule.Normal; _transmitnl = NewLine.CR; _renderProfile = null; _shellSchemeName = ShellSchemeCollection.DEFAULT_SCHEME_NAME; _enabledCharTriggerIntelliSense = false; _multiLogSettings = new MultiLogSettings(); _listeners = new ListenerList<ITerminalSettingsChangeListener>(); }
public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB, EncodingType type) { Assert.AreNotEqual(outputA, outputB); Assert.AreNotEqual(outputA, inputA); Assert.AreNotEqual(outputA, inputB); Assert.AreNotEqual(outputB, inputA); Assert.AreNotEqual(outputB, inputB); Assert.AreNotEqual(inputA, inputB); m_dio1 = new DioCrossConnectFixture(inputA, outputA); m_dio2 = new DioCrossConnectFixture(inputB, outputB); m_allocated = true; m_sourcePort[0] = outputA; m_sourcePort[1] = outputB; m_encoderPort[0] = inputA; m_encoderPort[1] = inputB; m_source = new FakeEncoderSource(m_dio1.GetOutput(), m_dio2.GetOutput()); m_encoder = new Encoder(m_dio1.GetInput(), m_dio2.GetInput(), false, type); }
public static EncodingProfile Get(EncodingType et) { EncodingProfile p = null; switch(et) { case EncodingType.ISO8859_1: p = new ISO8859_1Profile(); break; case EncodingType.EUC_JP: p = new EUCJPProfile(); break; case EncodingType.SHIFT_JIS: p = new ShiftJISProfile(); break; case EncodingType.UTF8: p = new UTF8Profile(); break; } return p; }
/// <summary> /// Converts a string to a byte array using specified encoding. /// </summary> /// <param name="str">String to be converted.</param> /// <param name="encodingType">EncodingType enum.</param> /// <returns>byte array</returns> public static byte[] StringToByteArray(string str, EncodingType encodingType) { System.Text.Encoding encoding=null; switch (encodingType) { case EncodingType.ASCII: encoding= new System.Text.ASCIIEncoding(); break; case EncodingType.Unicode: encoding = new System.Text.UnicodeEncoding(); break; case EncodingType.UTF7: encoding = new System.Text.UTF7Encoding(); break; case EncodingType.UTF8: encoding = new System.Text.UTF8Encoding(); break; } return encoding.GetBytes(str); }
public static string ByteArrayToString(byte[] bytes, EncodingType encodingType) { System.Text.Encoding encoding = null; switch (encodingType) { case EncodingType.ASCII: encoding = new System.Text.ASCIIEncoding(); break; case EncodingType.Unicode: encoding = new System.Text.UnicodeEncoding(); break; case EncodingType.UTF7: encoding = new System.Text.UTF7Encoding(); break; case EncodingType.UTF8: encoding = new System.Text.UTF8Encoding(); break; } return encoding.GetString(bytes); }
public static IList <string> GetFileLines(string path, string lineToMatch, bool caseSensitive = true, EncodingType encoding = FileEncoding) { IList <string> matchedLines = new List <string>(); if (System.IO.File.Exists(path)) { IEnumerable <string> lines = System.IO.File.ReadLines(path, GetEncoding(encoding)); foreach (string line in lines) { if (caseSensitive ? line.Contains(lineToMatch) : line.ToLower().Contains(lineToMatch.ToLower())) { matchedLines.Add(line); } } } return(matchedLines); }
public static string ReadString(EncodingType textEncoding, Stream stream, int length) { string text1; byte[] buffer1 = Utils.Read(stream, length); if (textEncoding == EncodingType.ISO88591) { text1 = Utils.ISO88591GetString(buffer1); } else if (textEncoding == EncodingType.Unicode) { if (length > 2) { if (buffer1.Length >= 2) { if ((buffer1[0] == 0xff) && (buffer1[1] == 0xfe)) { text1 = Encoding.Unicode.GetString(buffer1, 2, buffer1.Length - 2); } else if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); } else { text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = ""; } } else if (textEncoding == EncodingType.UTF16BE) { if (buffer1.Length >= 2) { if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); } else { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 0, buffer1.Length); } } else if (textEncoding == EncodingType.UTF8) { text1 = Encoding.UTF8.GetString(buffer1, 0, length); } else { string text2 = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(text2); return(""); } return(text1.TrimEnd(new char[1])); }
public RequestParameterType() { this.ParameterRequiredIndicator = true; this.ParameterEncoding = EncodingType.None; this.ParameterOccurrenceNumber = "1"; }
private static string ToSHA256(string str, EncodingType encodingType) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(str); return(ToSHA256(plainTextBytes, encodingType)); }
public async global::System.Threading.Tasks.Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.I32) { F = (Flag)await iprot.ReadI32Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 2: if (field.Type == TType.List) { { TList _list235 = await iprot.ReadListBeginAsync(cancellationToken); K = new List <byte[]>(_list235.Count); for (int _i236 = 0; _i236 < _list235.Count; ++_i236) { byte[] _elem237; _elem237 = await iprot.ReadBinaryAsync(cancellationToken); K.Add(_elem237); } await iprot.ReadListEndAsync(cancellationToken); } } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 3: if (field.Type == TType.I64) { Ts = await iprot.ReadI64Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 4: if (field.Type == TType.Bool) { Ts_desc = await iprot.ReadBoolAsync(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 5: if (field.Type == TType.String) { V = await iprot.ReadBinaryAsync(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 6: if (field.Type == TType.I32) { Encoder = (EncodingType)await iprot.ReadI32Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); } finally { iprot.DecrementRecursionDepth(); } }
public async global::System.Threading.Tasks.Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.I64) { Ts = await iprot.ReadI64Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 2: if (field.Type == TType.List) { { TList _list89 = await iprot.ReadListBeginAsync(cancellationToken); V = new List <CellValueSerial>(_list89.Count); for (int _i90 = 0; _i90 < _list89.Count; ++_i90) { CellValueSerial _elem91; _elem91 = new CellValueSerial(); await _elem91.ReadAsync(iprot, cancellationToken); V.Add(_elem91); } await iprot.ReadListEndAsync(cancellationToken); } } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 3: if (field.Type == TType.I32) { Encoder = (EncodingType)await iprot.ReadI32Async(cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); } finally { iprot.DecrementRecursionDepth(); } }
public static bool ReplaceInFile(string path, string oldContent, string newContent, EncodingType encoding = FileEncoding) { if (!System.IO.File.Exists(path)) { return(false); } string fileContent = System.IO.File.ReadAllText(path, GetEncoding(encoding)); System.IO.File.WriteAllText(path, fileContent.Replace(oldContent, newContent), GetEncoding(encoding)); return(true); }
public static bool ReplaceLineInFile(string path, string content, int lineIndex, bool keepIndentation = false, EncodingType encoding = FileEncoding) { if (!System.IO.File.Exists(path) || lineIndex < 0) { return(false); } string[] lines = System.IO.File.ReadAllLines(path, GetEncoding(encoding)); if (lineIndex >= lines.Length) { return(false); } lines[lineIndex] = keepIndentation ? lines[lineIndex].GetStartTabsWhitespaces() + content : content; System.IO.File.WriteAllLines(path, lines, GetEncoding(encoding)); return(true); }
public static bool InsertBetweenInFile(string path, string content, string start, string end, EncodingType encoding = FileEncoding) { if (!System.IO.File.Exists(path)) { return(false); } string fileContent = System.IO.File.ReadAllText(path, GetEncoding(encoding)); string contentBetween = fileContent.StringBetween(start, end); content = start + contentBetween + content + end; System.IO.File.WriteAllText(path, fileContent.Replace(start + contentBetween + end, content), GetEncoding(encoding)); return(true); }
/// <summary> /// Sets the encoding in which the file will be interpreted upon reading it from the disc. /// To see a change in the representation, the content needs to be read again. /// </summary> /// <param name="type">The given type of input encoding.</param> public void SetInputEncoding(EncodingType type) { InputEncoding = Encodings.GetEncoding(type); }
private async Task <int> Work(string filePath, string cookiePath) { string cookie = File.ReadAllText(cookiePath, EncodingType.GetType(cookiePath)); var fileEncoding = EncodingType.GetType(filePath); var fileContent = File.ReadAllText(filePath, fileEncoding); var fileInfo = new FileInfo(filePath); var fileExtension = fileInfo.Extension; var fileDir = fileInfo.DirectoryName; var imgProc = new ImageProcessor(); var imgList = imgProc.Process(fileContent); Console.WriteLine($"提取图片成功,共{imgList.Count}个."); var uploader = new ClientUploader("https://www.imooc.com"); var replaceDic = new Dictionary <string, string>(); foreach (var img in imgList) { string imgPhyPath = Path.Combine(fileDir, img); Console.WriteLine($"正在上传图片:{imgPhyPath}"); try { var res = await uploader.UploadAsync(imgPhyPath, "/article/ajaxuploadimg", "photo", new Dictionary <string, string>() { ["Cookie"] = cookie }); //校验 var json = JObject.Parse(res); if (json.Value <int>("result") != 0) { Console.WriteLine("Cookie无效!"); return(1); } var httpImgPath = json["data"].Value <string>("imgpath"); replaceDic.Add(img, httpImgPath); Console.WriteLine("上传成功!"); } catch (Exception e) { Console.WriteLine($"处理失败!{e.Message}"); return(1); } } var newContent = imgProc.Replace(replaceDic, fileContent); string newFileName = filePath.Substring(0, filePath.LastIndexOf('.')) + "-imooc" + fileExtension; File.WriteAllText(newFileName, newContent, fileEncoding); Console.WriteLine($"处理完成!文件保存在:{newFileName}"); return(0); }
public RawDontTerminateLengthPrefixedStringTypeSerializationGenerator([NotNull] ITypeSymbol actualType, [NotNull] ISymbol member, SerializationMode mode, EncodingType encoding, PrimitiveSizeType sizeType) : base(actualType, member, mode, encoding) { if (!Enum.IsDefined(typeof(PrimitiveSizeType), sizeType)) { throw new InvalidEnumArgumentException(nameof(sizeType), (int)sizeType, typeof(PrimitiveSizeType)); } SizeType = sizeType; }
public static bool InsertInFile(string path, string content, int lineIndex, bool insertAfterLine = false, EncodingType encoding = FileEncoding) { if (!System.IO.File.Exists(path) || lineIndex < 0) { return(false); } string[] lines = System.IO.File.ReadAllLines(path, GetEncoding(encoding)); if (lineIndex >= lines.Length) { return(false); } lines[lineIndex] = insertAfterLine ? lines[lineIndex] + content : content + lines[lineIndex]; System.IO.File.WriteAllLines(path, lines, GetEncoding(encoding)); return(true); }
public static string GetFileLine(string path, string lineToMatch, bool caseSensitive = true, EncodingType encoding = FileEncoding) { if (!System.IO.File.Exists(path)) { return(string.Empty); } IEnumerable <string> lines = System.IO.File.ReadLines(path, GetEncoding(encoding)); foreach (string line in lines) { if (caseSensitive ? line.Contains(lineToMatch) : line.ToLower().Contains(lineToMatch.ToLower())) { return(line); } } return(string.Empty); }
public static string ReadString(EncodingType textEncoding, Stream stream, ref int bytesLeft) { string text1; if (bytesLeft > 0) { List <byte> list1 = new List <byte>(); if (textEncoding != EncodingType.ISO88591) { if (textEncoding == EncodingType.Unicode) { byte num2; byte num3; do { num2 = Utils.ReadByte(stream); list1.Add(num2); bytesLeft -= 1; if (bytesLeft == 0) { return(""); } num3 = Utils.ReadByte(stream); list1.Add(num3); bytesLeft -= 1; }while ((bytesLeft != 0) && ((num2 != 0) || (num3 != 0))); byte[] buffer1 = list1.ToArray(); if (buffer1.Length >= 2) { if ((buffer1[0] == 0xff) && (buffer1[1] == 0xfe)) { text1 = Encoding.Unicode.GetString(buffer1, 2, buffer1.Length - 2); goto Label_027D; } if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); goto Label_027D; } text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); goto Label_027D; } text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); goto Label_027D; } if (textEncoding == EncodingType.UTF16BE) { byte num4; byte num5; do { num4 = Utils.ReadByte(stream); list1.Add(num4); bytesLeft -= 1; if (bytesLeft == 0) { return(""); } num5 = Utils.ReadByte(stream); list1.Add(num5); bytesLeft -= 1; }while ((bytesLeft != 0) && ((num4 != 0) || (num5 != 0))); byte[] buffer2 = list1.ToArray(); if (buffer2.Length >= 2) { if ((buffer2[0] == 0xfe) && (buffer2[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer2, 2, buffer2.Length - 2); goto Label_027D; } text1 = Encoding.BigEndianUnicode.GetString(buffer2, 0, buffer2.Length); goto Label_027D; } text1 = Encoding.BigEndianUnicode.GetString(buffer2, 0, buffer2.Length); goto Label_027D; } if (textEncoding != EncodingType.UTF8) { string text2 = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(text2); return(""); } byte num6 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft != 0) { while (num6 != 0) { list1.Add(num6); num6 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft == 0) { return(""); } } text1 = Encoding.UTF8.GetString(list1.ToArray()); goto Label_027D; } return(""); } byte num1 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft != 0) { while (num1 != 0) { list1.Add(num1); num1 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft == 0) { if (num1 != 0) { list1.Add(num1); } return(Utils.ISO88591GetString(list1.ToArray())); } } text1 = Utils.ISO88591GetString(list1.ToArray()); goto Label_027D; } } return(""); Label_027D: return(text1.TrimEnd(new char[1])); }
public UsernameToken(string username, string password, PasswordOption passType, EncodingType encType) { this.Username = new Username(); this.Username.Text = username; System.Guid g = GuidEx.NewGuid(); this.Id = "SecurityToken-" + g.ToString("D"); if (passType == PasswordOption.SendNone) { this.Password = null; DateTime dtCreated = DateTime.UtcNow; this.Created = XmlConvert.ToString(dtCreated, "yyyy-MM-ddTHH:mm:ssZ"); this.Nonce = new Nonce(); byte [] baNonce = OpenNETCF.Security.Cryptography.NativeMethods.Rand.GetRandomBytes(20); this.Nonce.Text = Convert.ToBase64String(baNonce, 0, baNonce.Length); return; } this.Password = new Password(); if (passType == PasswordOption.SendPlainText) { //this.Password.Type = "wsse:PasswordText"; this.Password.Type = Misc.tokenProfUsername + "#PasswordText"; this.Password.Text = password; } if (passType == PasswordOption.SendHashed) { //this.Password.Type = "wsse:PasswordDigest"; this.Password.Type = Misc.tokenProfUsername + "#PasswordDigest"; DateTime dtCreated = DateTime.UtcNow; this.Created = XmlConvert.ToString(dtCreated, "yyyy-MM-ddTHH:mm:ssZ"); byte [] baCreated = Encoding.UTF8.GetBytes(this.Created); this.Nonce = new Nonce(); //this random number gen is not as strong //Random r = new Random(Environment.TickCount); //byte [] baNonce = new byte[20]; //r.NextBytes(baNonce); byte [] baNonce = OpenNETCF.Security.Cryptography.NativeMethods.Rand.GetRandomBytes(20); this.Nonce.Text = Convert.ToBase64String(baNonce, 0, baNonce.Length); byte [] baPassword = Encoding.UTF8.GetBytes(password); int baDigestLength = baNonce.Length + baCreated.Length + baPassword.Length; byte [] baDigest = new byte[baDigestLength]; Array.Copy(baNonce, 0, baDigest, 0, baNonce.Length); Array.Copy(baCreated, 0, baDigest, baNonce.Length, baCreated.Length); Array.Copy(baPassword, 0, baDigest, baNonce.Length + baCreated.Length, baPassword.Length); //byte [] hash = Hash.ComputeHash(CalgHash.SHA1, baDigest); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte [] hash = sha1.ComputeHash(baDigest); if (encType == EncodingType.Base64Binary) { //default is Base64Binary so dont have to set //this.Password.Type = "wsse:Base64Binary"; this.Password.Text = Convert.ToBase64String(hash, 0, hash.Length); } if (encType == EncodingType.HexBinary) { //this.Password.Type = "wsse:HexBinary"; this.Password.Type = Misc.tokenProfUsername + "#HexBinary"; this.Password.Text = OpenNETCF.Security.Cryptography.NativeMethods.Format.GetHexBin(hash); } } }
public static byte[] GetStringBytes(ID3v2TagVersion tagVersion, EncodingType encodingType, string value, bool isTerminated) { List <byte> list1 = new List <byte>(); switch (tagVersion) { case ID3v2TagVersion.ID3v22: { EncodingType type1 = encodingType; if (type1 == EncodingType.Unicode) { if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; } list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; } case ID3v2TagVersion.ID3v23: { EncodingType type2 = encodingType; if (type2 != EncodingType.Unicode) { list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; } if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; } case ID3v2TagVersion.ID3v24: switch (encodingType) { case EncodingType.Unicode: if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; case EncodingType.UTF16BE: if (!string.IsNullOrEmpty(value)) { list1.AddRange(Encoding.BigEndianUnicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; case EncodingType.UTF8: if (!string.IsNullOrEmpty(value)) { list1.AddRange(Encoding.UTF8.GetBytes(value)); } if (isTerminated) { list1.Add(0); } break; } list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; default: throw new ArgumentException("Unknown tag version"); } return(list1.ToArray()); }
private async Task <int> Work(string filePath, string cookiePath) { string cookie = File.ReadAllText(cookiePath, EncodingType.GetType(cookiePath)); var fileEncoding = EncodingType.GetType(filePath); var fileContent = File.ReadAllText(filePath, fileEncoding); var fileInfo = new FileInfo(filePath); var fileExtension = fileInfo.Extension; var fileDir = fileInfo.DirectoryName; var imgProc = new ImageProcessor(); var imgList = imgProc.Process(fileContent); Console.WriteLine($"提取图片成功,共{imgList.Count}个."); var uploader = new ClientUploader("https://cloud.tencent.com"); var replaceDic = new Dictionary <string, string>(); foreach (var img in imgList) { string imgPhyPath = Path.Combine(fileDir, img); Console.WriteLine($"正在上传图片:{imgPhyPath}"); try { var res = await uploader.UploadAsync(imgPhyPath, $"/developer/services/ajax/image?action=UploadImage&uin={Uin}&csrfCode={Csrf}", "image", new Dictionary <string, string>() { ["Cookie"] = cookie }); //校验 var json = JObject.Parse(res); if (json.Value <int>("code") != 0) { Console.WriteLine("Cookie或uin、csrf code 无效!"); return(1); } var httpImgPath = json["data"].Value <string>("url"); replaceDic.Add(img, httpImgPath); Console.WriteLine("上传成功!"); } catch (Exception e) { Console.WriteLine($"处理失败!{e.Message}"); return(1); } } var newContent = imgProc.Replace(replaceDic, fileContent); string newFileName = filePath.Substring(0, filePath.LastIndexOf('.')) + "-tcloud" + fileExtension; File.WriteAllText(newFileName, newContent, fileEncoding); Console.WriteLine($"处理完成!文件保存在:{newFileName}"); return(0); }
public static string GetStringFromArray(this byte[] self, EncodingType encoder) { var enc = EncodingTypeFactory.CreateEncoder(encoder); return(enc.GetString(self)); }
public static IList <string> GetFileLines(string path, string lineToMatch, bool caseSensitive = true, EncodingType encoding = FileEncoding, params string[] othersLinesToMatch) { IList <string> matchedLines = new List <string>(); if (System.IO.File.Exists(path)) { IEnumerable <string> lines = System.IO.File.ReadLines(path, GetEncoding(encoding)); foreach (string line in lines) { bool matchedLine = false; if (caseSensitive ? line.Contains(lineToMatch) : line.ToLower().Contains(lineToMatch.ToLower())) { matchedLines.Add(line); matchedLine = true; } for (int i = 0; !matchedLine && i < othersLinesToMatch.Length; ++i) { if (caseSensitive ? line.Contains(othersLinesToMatch[i]) : line.ToLower().Contains(othersLinesToMatch[i].ToLower())) { matchedLines.Add(line); matchedLine = true; } } } } return(matchedLines); }
public static bool InsertLineBetweenInFile(string path, string content, string start, string end, EncodingType encoding = FileEncoding) { return(InsertBetweenInFile(path, content + "\n", start, end, encoding)); }
public T2B(string filename) { using (BinaryReaderX br = new BinaryReaderX(File.OpenRead(filename))) { //Get Encoding br.BaseStream.Position = br.BaseStream.Length - 0xa; encoding = (EncodingType)br.ReadByte(); br.BaseStream.Position = 0; //Header header = br.ReadStruct <Header>(); //Entries for (int i = 0; i < header.entryCount; i++) { br.ReadInt32(); var entryLength = br.ReadByte(); br.BaseStream.Position -= 0x5; var entry = new StringEntry { entryTypeID = br.ReadUInt32(), entryLength = br.ReadByte(), typeMask = br.ReadBytes((entryLength > 10) ? 7 : 3) }; //cultivate data var mask = entry.typeMask.Reverse().ToList(); for (int j = 0; j < mask.Count; j++) { for (int count = 0; count < 8; count += 2) { var type = (byte)((mask[j] & (0x3 << count)) >> count); if (type != 0x3) { entry.data.Add(new StringEntry.TypeEntry { type = type, value = br.ReadUInt32() }); } if (entry.data.Count == entry.entryLength) { break; } } if (entry.data.Count == entry.entryLength) { break; } } entries.Add(entry); } //Text var id = 0; for (var ctry = 0; ctry < entries.Count; ctry++) { for (var ctrx = 0; ctrx < entries[ctry].data.Count; ctrx++) { var d = entries[ctry].data[ctrx]; if (d.type == 0) { if (d.value != 0xffffffff) { int index = -1; for (var i = 0; i < Labels.Count; i++) { if (Labels[i].relOffset == d.value) { index = i; } } if (index == -1) { br.BaseStream.Position = header.stringSecOffset + d.value; Labels.Add(new Label { Text = GetDecodedText(GetStringBytes(br.BaseStream), encoding).Replace("\\n", "\n"), TextID = id, Name = $"text{id++:0000}", relOffset = d.value }); Labels[Labels.Count - 1].Points.Add(new Point { X = ctrx, Y = ctry }); } else { Labels[index].Points.Add(new Point { X = ctrx, Y = ctry }); } } } } } //signature br.BaseStream.Position = (br.BaseStream.Position + 0xf) & ~0xf; sig = br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)); } }
public static Encoding GetFileCharset(string filePath) { return(EncodingType.GetType(filePath)); }
private static string ToMd5(string input, EncodingType encodingType) { byte[] inputBytes = Encoding.ASCII.GetBytes(input); return(CreateMd5(inputBytes, encodingType)); }
public static bool InsertLineInFile(string path, string content, int lineIndex, bool insertAfterFile = false, EncodingType encoding = FileEncoding) { return(InsertInFile(path, content + "\n", lineIndex, insertAfterFile, encoding)); }
internal static void CheckAccess(Validation.ValidationContext result, BufferView bv, int accessorByteOffset, DimensionType dim, EncodingType enc, bool nrm, int count) { if (nrm) { if (enc != EncodingType.UNSIGNED_BYTE && enc != EncodingType.UNSIGNED_SHORT) { result.AddDataError("Normalized", "Only (u)byte and (u)short accessors can be normalized."); } } var elementByteSize = dim.DimCount() * enc.ByteLength(); if (bv.IsVertexBuffer) { if (bv.ByteStride == 0) { result.CheckSchemaIsMultipleOf("ElementByteSize", elementByteSize, 4); } } if (bv.IsIndexBuffer) { if (dim != DimensionType.SCALAR) { result.AddLinkError(("BufferView", bv.LogicalIndex), $"is an IndexBuffer, but accessor dimensions is: {dim}"); } // TODO: these could by fixed by replacing BYTE by UBYTE, SHORT by USHORT, etc if (enc == EncodingType.BYTE) { result.AddLinkError(("BufferView", bv.LogicalIndex), $"is an IndexBuffer, but accessor encoding is (s)byte"); } if (enc == EncodingType.SHORT) { result.AddLinkError(("BufferView", bv.LogicalIndex), $"is an IndexBuffer, but accessor encoding is (s)short"); } if (enc == EncodingType.FLOAT) { result.AddLinkError(("BufferView", bv.LogicalIndex), $"is an IndexBuffer, but accessor encoding is float"); } if (nrm) { result.AddLinkError(("BufferView", bv.LogicalIndex), $"is an IndexBuffer, but accessor is normalized"); } } if (bv.ByteStride > 0) { if (bv.ByteStride < elementByteSize) { result.AddLinkError("ElementByteSize", $"Referenced bufferView's byteStride value {bv.ByteStride} is less than accessor element's length {elementByteSize}."); } // "Accessor's total byteOffset {0} isn't a multiple of componentType length {1}."; return; } var accessorByteLength = bv.GetAccessorByteLength(dim, enc, count); // "Accessor(offset: {0}, length: {1}) does not fit referenced bufferView[% 3] length %4."; result.CheckArrayRangeAccess(("BufferView", bv.LogicalIndex), accessorByteOffset, accessorByteLength, bv.Content); }
private MMALEncoding(string s, EncodingType type) { this.EncodingVal = Helpers.FourCCFromString(s); this.EncodingName = s; this.EncType = type; }
private static void ExportFile(DialogueDatabase database, string language, string baseFilename, EncodingType encodingType) { var filename = string.IsNullOrEmpty(language) ? baseFilename : Path.GetDirectoryName(baseFilename) + "/" + Path.GetFileNameWithoutExtension(baseFilename) + "_" + language + ".csv"; using (StreamWriter file = new StreamWriter(filename, false, EncodingTypeTools.GetEncoding(encodingType))) { ExportConversations(database, language, file); } }
private MMALEncoding(int val, string name, EncodingType type) { this.EncodingVal = val; this.EncodingName = name; this.EncType = type; }
public static bool AddLineInFile(string path, IEnumerable <string> content, EncodingType encoding = FileEncoding) { return(AddInFile(path, content.Select(value => "\n" + value), encoding)); }