public HeaderInfo ( System.Collections.Specialized.HybridDictionary headers ) { this.TopLevelMediaType = new anmar.SharpMimeTools.MimeTopLevelMediaType(); this.enc = null; try { this.contenttype = anmar.SharpMimeTools.SharpMimeTools.parseHeaderFieldBody ( "Content-Type", headers["Content-Type"].ToString() ); this.TopLevelMediaType = (anmar.SharpMimeTools.MimeTopLevelMediaType)System.Enum.Parse(TopLevelMediaType.GetType(), this.contenttype["Content-Type"].Split('/')[0].Trim(), true); this.subtype = this.contenttype["Content-Type"].Split('/')[1].Trim(); this.enc = anmar.SharpMimeTools.SharpMimeTools.parseCharSet ( this.contenttype["charset"] ); } catch (System.Exception) { this.enc = anmar.SharpMimeTools.SharpMimeHeader.default_encoding; this.contenttype = anmar.SharpMimeTools.SharpMimeTools.parseHeaderFieldBody ( "Content-Type", System.String.Concat("text/plain; charset=", this.enc.BodyName) ); this.TopLevelMediaType = anmar.SharpMimeTools.MimeTopLevelMediaType.text; this.subtype = "plain"; } if ( this.enc==null ) { this.enc = anmar.SharpMimeTools.SharpMimeHeader.default_encoding; } // TODO: rework this try { this.contentdisposition = anmar.SharpMimeTools.SharpMimeTools.parseHeaderFieldBody ( "Content-Disposition", headers["Content-Disposition"].ToString() ); } catch ( System.Exception ) { this.contentdisposition = new System.Collections.Specialized.StringDictionary(); } try { this.contentlocation = anmar.SharpMimeTools.SharpMimeTools.parseHeaderFieldBody ( "Content-Location", headers["Content-Location"].ToString() ); } catch ( System.Exception ) { this.contentlocation = new System.Collections.Specialized.StringDictionary(); } }
internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder, byte lineDelimiter) { Data = data; TcpClient = tcpClient; _encoder = stringEncoder; _writeLineDelimiter = lineDelimiter; }
//Direct Compression/Decompression public CompressString(System.Text.Encoding TextEncoding, string InputString, InputDataTypeClass InputDataType, string Passphrase = "", string PrefixForCompressedString = "", string SuffixForCompressedString = "") { this._TextEncoding = TextEncoding; this._PrefixForCompressedString = PrefixForCompressedString; this._SuffixForCompressedString = SuffixForCompressedString; this._Passphrase = Passphrase; switch (InputDataType) { case InputDataTypeClass.UnCompressed: this._UnCompressed = InputString; this.Compress(); break; case InputDataTypeClass.Compressed: string Result = InputString; if (Result.Length > 0 & Result.Length > (this._PrefixForCompressedString.Length + this._SuffixForCompressedString.Length)) { if (this._PrefixForCompressedString.Length > 0) { Result = InputString.Substring(this._PrefixForCompressedString.Length, Result.Length - this._PrefixForCompressedString.Length); } if (this._SuffixForCompressedString.Length > 0) { Result = Result.Substring(0, Result.Length - this._SuffixForCompressedString.Length); } } this._Compressed = Result; this._CompressedGiven = true; this.Decompress(); break; } }
private static string ReadAllText(string path, Encoding encoding) { using (var reader = new StreamReader(path, encoding ?? Encoding.Default)) { return reader.ReadToEnd(); } }
public static Action<HttpContextBase> Create(IEnumerable<string> resourceNames, string mediaType, Encoding responseEncoding, bool cacheResponse) { Debug.Assert(resourceNames != null); Debug.AssertStringNotEmpty(mediaType); return context => { // // Set the response headers for indicating the content type // and encoding (if specified). // var response = context.Response; response.ContentType = mediaType; if (cacheResponse) { response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetExpires(DateTime.MaxValue); } if (responseEncoding != null) response.ContentEncoding = responseEncoding; foreach (var resourceName in resourceNames) ManifestResourceHelper.WriteResourceToStream(response.OutputStream, resourceName); }; }
internal static string UrlEncode(string str, Encoding e) { if (str == null) return null; return Encoding.ASCII.GetString(UrlEncodeToBytes(str, e)); }
/// <summary> /// Creates a new instance of this class. /// </summary> /// <param name="encoding">The encoding.</param> public CsvOptions(System.Text.Encoding encoding) { // Initialize field members. this._encoding = encoding; this._hasHeader = false; this._seperator = ','; this._stringCharacter = '"'; }
public ManifestResourceHandler(string resourceName, string contentType, Encoding responseEncoding) { Debug.AssertStringNotEmpty(resourceName); Debug.AssertStringNotEmpty(contentType); _resourceName = resourceName; _contentType = contentType; _responseEncoding = responseEncoding; }
/// <summary> /// Constructor. /// </summary> /// <param name="modelData"></param> public DefaultContextModelContextBase(DslEditorModeling::ModelData modelData) : base(modelData) { encodingXml = System.Text.Encoding.GetEncoding("ISO-8859-1"); //validationController = VSPluginDSLValidationController.Instance; //validationController.Initialize(); serializationResult = new DslEditorModeling::SerializationResult(); }
/// <summary> /// Creates new intstance of HD44780 LCD display in 4-bit mode. /// </summary> /// <param name="provider">Data transfer provider.</param> public LCD4Bit(ITransferProvider provider) { this.Provider = provider; this.Encoding = System.Text.Encoding.UTF8; this._backLight = false; Init(true); }
public virtual void Load( string fileName, Encoding encoding ) { if ( fileName == null ) { return; } data = System.IO.File.ReadAllText( fileName, encoding ).ToCharArray(); n = data.Length; }
static System.IO.FileStream fs; //файловый поток - (запись/чтение) в файл двоичных данных #endregion Fields #region Methods static void Main() { enc = System.Text.Encoding.GetEncoding(1251); fs = new System.IO.FileStream("log.txt", System.IO.FileMode.Create , System.IO.FileAccess.Write ); //на запись bw = new System.IO.BinaryWriter(fs, enc); //инициализация файловым потоком, с указанием рабочей кодировки //по умолчанию запись идет в кодировке utf8 SayFile("{0} - {1} - {2}", "Hello", "File", "Приветик"); fs.Close(); }
//New implementation of the CreateAndRegisterStream method // Using in Render public System.IO.Stream IntermediateCreateAndRegisterStream(string name, string extension, System.Text.Encoding encoding, string mimeType , bool willSeek, Microsoft.ReportingServices.Interfaces.StreamOper operation) { _name = name; _encoding = encoding; _extension = extension; _mimeType = mimeType; _operation = operation; _willSeek = willSeek; intermediateStream = new System.IO.MemoryStream(); return intermediateStream; }
public RemapEncoding(int codePage) : base(codePage) { if (codePage == 28591) { encodingEncoding = System.Text.Encoding.GetEncoding(28591); decodingEncoding = System.Text.Encoding.GetEncoding(1252); } else { if (codePage != 28599) throw new System.ArgumentException(); encodingEncoding = System.Text.Encoding.GetEncoding(28599); decodingEncoding = System.Text.Encoding.GetEncoding(1254); } }
public ANTLRInputStream( Stream input, int size, int readBufferSize, Encoding encoding ) { StreamReader isr; if ( encoding != null ) { isr = new StreamReader( input, encoding ); } else { isr = new StreamReader( input ); } Load( isr, size, readBufferSize ); }
public virtual void Load( string fileName, Encoding encoding ) { if ( fileName == null ) { return; } string text; if (encoding == null) text = File.ReadAllText(fileName); else text = File.ReadAllText(fileName, encoding); data = text.ToCharArray(); n = data.Length; }
public virtual void Load( string fileName, Encoding encoding ) { if ( fileName == null ) { return; } throw new System.NotSupportedException(); /* string text; if (encoding == null) text = File.re.ReadAllText(fileName); else text = File.ReadAllText(fileName, encoding); data = text.ToCharArray(); n = data.Length;*/ }
static Encoding() { defLangMap.Add("English", new FontLangInfo(1252, 1033, 0)); defLangMap.Add("Czech", new FontLangInfo(1252, 1029, 238)); defLangMap.Add("French", new FontLangInfo(1252, 1036, 0)); defLangMap.Add("German", new FontLangInfo(1252, 1031, 0)); defLangMap.Add("Italian", new FontLangInfo(1252, 1040, 0)); defLangMap.Add("Spanish", new FontLangInfo(1252, 1034, 0)); defLangMap.Add("Russian", new FontLangInfo(1251, 1049, 204)); defLangMap.Add("Polish", new FontLangInfo(1250, 1045, 0)); defLangMap.Add("Japanese", new FontLangInfo(932, 1041, 128)); //128 => i'm not sure but i find on the web SHIFTJIS_CHARSET = 128 //http://www.tek-tips.com/viewthread.cfm?qid=712495 //Private Const DEFAULT_CHARSET = 1 //Private Const SYMBOL_CHARSET = 2 //Private Const SHIFTJIS_CHARSET = 128 //Private Const HANGEUL_CHARSET = 129 //Private Const CHINESEBIG5_CHARSET = 136 //Private Const CHINESESIMPLIFIED_CHARSET = 134 CP1252 = Properties.Settings.Default.UseUTF8 ? s_UTF8Encoding : s_CP1252Encoding; }
/// <exception cref="System.IO.IOException"/> public virtual void Load(string fileName, Encoding encoding) { if (fileName == null) { return; } string text; #if !COMPACT if (encoding != null) text = File.ReadAllText(fileName, encoding); else text = File.ReadAllText(fileName); #else if (encoding != null) text = ReadAllText(fileName, encoding); else text = ReadAllText(fileName); #endif data = text.ToCharArray(); n = data.Length; }
public void SetEncoding(string encoding) { encoding = encoding.ToUpper(); if (encoding == "UTF-8") this.encoding = System.Text.Encoding.UTF8; else if (encoding == "UTF-16") this.encoding = System.Text.Encoding.Unicode; else if (encoding == "UTF-7") this.encoding = System.Text.Encoding.UTF7; else if (encoding == "US-ASCII") this.encoding = System.Text.Encoding.ASCII; else { try { this.encoding = System.Text.Encoding.GetEncoding( encoding ); } catch( NotSupportedException ) { throw new XmlException("Unknown encoding"); } } }
internal EntityBodyInspector(HttpUploadWorkerRequest request) { statistic = new UploadProgressStatistic(); statistic.TotalBytes = request.GetTotalEntityBodyLength(); string contentType = request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType); string boundary = string.Format("--{0}\r\n", UploadProgressUtils.GetBoundary(contentType)); _encoding = System.Text.Encoding.UTF8; _boundaryWaiter = new EntityBodyChunkStateWaiter(boundary, false); _boundaryWaiter.MeetGuard += new EventHandler<EventArgs>(boundaryWaiter_MeetGuard); _current = _boundaryWaiter; _boundaryInfoWaiter = new EntityBodyChunkStateWaiter("\r\n\r\n", true); _boundaryInfoWaiter.MeetGuard += new EventHandler<EventArgs>(boundaryInfoWaiter_MeetGuard); _formValueWaiter = new EntityBodyChunkStateWaiter("\r\n", true); _formValueWaiter.MeetGuard += new EventHandler<EventArgs>(formValueWaiter_MeetGuard); _lastCdName = string.Empty; }
public void AppendAllText(string path, string contents, System.Text.Encoding encoding) => System.IO.File.AppendAllText(path, contents, encoding);
/// <summary>Loads a custom plugin for the specified train.</summary> /// <param name="trainFolder">The absolute path to the train folder.</param> /// <param name="encoding">The encoding to be used.</param> /// <returns>Whether the plugin was loaded successfully.</returns> internal bool LoadCustomPlugin(string trainFolder, System.Text.Encoding encoding) { string config = OpenBveApi.Path.CombineFile(trainFolder, "ats.cfg"); if (!System.IO.File.Exists(config)) { return(false); } string Text = System.IO.File.ReadAllText(config, encoding); Text = Text.Replace("\r", "").Replace("\n", ""); if (Text.Length > 260) { /* * String length is over max Windows path length, so * comments or ATS plugin docs have been included in here * e.g dlg70v40 */ string[] fileLines = System.IO.File.ReadAllLines(config); for (int i = 0; i < fileLines.Length; i++) { int commentStart = fileLines[i].IndexOf(';'); if (commentStart != -1) { fileLines[i] = fileLines[i].Substring(0, commentStart); } fileLines[i] = fileLines[i].Trim(); if (fileLines[i].Length != 0) { Text = fileLines[i]; break; } } } string file; try { file = OpenBveApi.Path.CombineFile(trainFolder, Text); } catch { Interface.AddMessage(MessageType.Error, true, "The train plugin path was malformed in " + config); return(false); } string title = System.IO.Path.GetFileName(file); if (!System.IO.File.Exists(file)) { if (Text.EndsWith(".dll") && encoding.Equals(System.Text.Encoding.Unicode)) { // Our filename ends with .dll so probably is not mangled Unicode Interface.AddMessage(MessageType.Error, true, "The train plugin " + title + " could not be found in " + config); return(false); } // Try again with ASCII encoding Text = System.IO.File.ReadAllText(config, System.Text.Encoding.GetEncoding(1252)); Text = Text.Replace("\r", "").Replace("\n", ""); try { file = OpenBveApi.Path.CombineFile(trainFolder, Text); } catch { Interface.AddMessage(MessageType.Error, true, "The train plugin path was malformed in " + config); return(false); } title = System.IO.Path.GetFileName(file); if (!System.IO.File.Exists(file)) { // Nope, still not found Interface.AddMessage(MessageType.Error, true, "The train plugin " + title + " could not be found in " + config); return(false); } } Program.FileSystem.AppendToLogFile("Loading train plugin: " + file); bool success = LoadPlugin(file, trainFolder); if (success == false) { Loading.PluginError = Translations.GetInterfaceString("errors_plugin_failure1").Replace("[plugin]", file); } else { Program.FileSystem.AppendToLogFile("Train plugin loaded successfully."); } return(success); }
private MemoryStream SerializeLogEvents(ICollection <LogzioLoggingEvent> logz, System.Text.Encoding encodingUtf8, bool useGzip) { var ms = new MemoryStream(logz.Count * 512); using (var sw = new StreamWriter(ms, encodingUtf8, 1024, true)) { bool firstItem = true; foreach (var logEvent in logz) { if (!firstItem) { sw.WriteLine(); } _jsonSerializer.Serialize(sw, logEvent.LogData); firstItem = false; } sw.Flush(); } ms.Position = 0; return(ms); }
public NetworkReader(Stream _input, System.Text.Encoding _encoding, bool _leaveOpen) : base(_input, _encoding, _leaveOpen) { }
public Boolean AcceptClient() { Console.WriteLine("クライアントと接続待ち。"); Client = Listener.AcceptTcpClient(); Console.WriteLine( string.Format("クライアント({0},{1})と接続しました。", ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Port) ); System.Net.Sockets.NetworkStream ns = Client.GetStream(); ns.ReadTimeout = ReadTimeout; ns.WriteTimeout = WriteTimeout; System.Text.Encoding enc = System.Text.Encoding.UTF8; Boolean disconnected = false; do { System.IO.MemoryStream ms = new System.IO.MemoryStream(); int resSize = 0; byte[] resBytes = new byte[1024]; try { do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } ms.Write(resBytes, 0, resSize); //ns.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); } catch (IOException e) { disconnected = true; Console.WriteLine("Read Timeoutで切断しました。" + e); } string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //Console.WriteLine("[" + resMsg + "]"); if (disconnected) { //メッセージ解析 //返信処理 Console.WriteLine("通信終了。"); } else { //メッセージ解析 disconnected = !msg.Input(resMsg); //msg.Input(resMsg); //返信処理 string sendMsg = msg.Output(); byte[] sendByte = enc.GetBytes(sendMsg + "\n"); byte[] sendData = msg.OutputBinary(); try { ns.Write(sendByte, 0, sendByte.Length); ns.Write(sendData, 0, sendData.Length); } catch (IOException e) { disconnected = true; Console.WriteLine("Write Timeoutで切断しました。" + e); } //Console.WriteLine("[" + sendMsg + "]" + " 送信。"); Console.WriteLine("送信 text:" + sendByte.Length.ToString() + "bytes, binary:" + sendData.Length.ToString()); } } while (!disconnected); ns.Close(); Client.Close(); return(true); }
public string ReadAllText(string path, System.Text.Encoding encoding) => System.IO.File.ReadAllText(path, encoding);
/// <summary> /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>. /// </summary> /// <param name='p_type'> /// Indica se é um arquivo ou um diretório. /// </param> /// <param name='p_completename'> /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual. /// </param> /// <param name='p_encryptedname'> /// Se o nome do arquivo está criptografado ou não. /// </param> /// <param name='p_separator'> /// Separador de diretórios do caminho completo do arquivo. /// </param> public File(Spartacus.Utils.FileType p_type, string p_completename, bool p_encryptedname, Spartacus.Utils.PathSeparator p_separator) { Spartacus.Utils.Cryptor v_cryptor; string v_completename; if (p_encryptedname) { try { v_cryptor = new Spartacus.Utils.Cryptor("spartacus"); v_completename = v_cryptor.Decrypt(p_completename); } catch (System.Exception) { v_completename = p_completename; } } else v_completename = p_completename; this.v_filetype = p_type; this.v_pathseparator = p_separator; this.v_name = this.GetBaseName(v_completename); this.v_extension = this.GetExtension(v_completename); this.v_path = this.GetPath(v_completename); this.v_size = -1; this.v_encoding = System.Text.Encoding.GetEncoding("utf-8"); this.v_protected = false; this.v_hidden = this.GetHidden(); }
/// <summary> /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>. /// </summary> /// <param name='p_type'> /// Indica se é um arquivo ou um diretório. /// </param> /// <param name='p_completename'> /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual. /// </param> /// <param name='p_encoding'> /// Codificação do arquivo. /// </param> public File(Spartacus.Utils.FileType p_type, string p_completename, System.Text.Encoding p_encoding) { this.v_filetype = p_type; this.v_pathseparator = Spartacus.Utils.PathSeparator.SLASH; this.v_name = this.GetBaseName(p_completename); this.v_extension = this.GetExtension(p_completename); this.v_path = this.GetPath(p_completename); this.v_size = -1; this.v_encoding = p_encoding; this.v_protected = false; this.v_hidden = this.GetHidden(); }
public StringWriterWithEncoding(System.Text.StringBuilder sb, System.Text.Encoding encoding) : base(sb) { this.encoding = encoding; }
public static string AsString(this Azure.Core.BinaryData data, System.Text.Encoding encoding) { throw null; }
public static Azure.Core.BinaryData Create(string data, System.Text.Encoding encoding) { throw null; }
public PListWriter(string filename, System.Text.Encoding encoding) : base(filename, encoding) { }
public void WriteAllLines(string path, string[] contents, System.Text.Encoding encoding) => System.IO.File.WriteAllLines(path, contents, encoding);
public IEnumerable <string> ReadLines(string path, System.Text.Encoding encoding) => System.IO.File.ReadLines(path, encoding);
public StringWriterWithEncoding(System.Text.Encoding encoding) { this.encoding = encoding; }
public string[] ReadAllLines(string path, System.Text.Encoding encoding) => System.IO.File.ReadAllLines(path, encoding);
public TemplateGroupFile(string fullyQualifiedFileName, Encoding encoding, char delimiterStartChar, char delimiterStopChar) : this(fullyQualifiedFileName, delimiterStartChar, delimiterStopChar) { if (encoding == null) throw new ArgumentNullException("encoding"); this.Encoding = encoding; }
public Boolean Input(string msg) { // //header string[] rowStr = msg.Split('\n'); string[] colStr; retmsg = ""; retByte = new Byte[] { }; string connect = "Close"; foreach (string s in rowStr) { string ws = s.Replace("\r", ""); colStr = ws.Split(':'); ws = ""; if (colStr[0].CompareTo("Connection") == 0) { connect = colStr[1]; Console.WriteLine(colStr[1]); } } colStr = rowStr[0].Split(' '); Boolean statusflag = true; //msg = msg.TrimEnd('\n'); //msg = msg.TrimEnd('\r'); msg = colStr[0]; Console.WriteLine("[" + msg + "]"); switch (msg) { case "GET": /* HTTP/0.9 404 Not Found * 指定されたURIのリソースを取り出す。HTTPの最も基本的な動作で、HTTP/0.9では唯一のメソッド。 */ Console.WriteLine("filePath" + colStr[1]); string fileName = @colStr[1]; fileName = fileName.TrimStart('/'); if (fileName.Length == 0) { fileName = "index.html"; } if (System.IO.File.Exists(fileName)) { Console.WriteLine("'" + fileName + "'は存在します。"); System.IO.FileInfo fi = new System.IO.FileInfo(fileName); //ファイルのサイズを取得 Console.WriteLine("ファイルサイズ:" + fi.Length + " bytes"); colStr = fileName.Split('.'); string fileType = colStr[colStr.Length - 1]; Console.WriteLine("ファイルタイプ:" + fileType); switch (fileType) { case "txt": case "html": case "htm": case "css": //System.Text.Encoding enc = System.Text.Encoding.UTF8; System.Text.Encoding enc = System.Text.Encoding.GetEncoding("Shift_JIS"); //テキストファイルの中身をすべて読み込む string c_str = System.IO.File.ReadAllText(fileName, enc); retByte = enc.GetBytes(c_str); retmsg = "HTTP/0.9 200 OK" + CRLF; //retmsg += "Content-Type: text/html; charset=UTF-8" + CRLF; //retmsg += "Server: private_httpd" + CRLF; //retmsg += "Status: 200 OK" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; retmsg += CRLF; break; case "jpg": case "jpeg": case "png": case "gif": case "ico": retByte = System.IO.File.ReadAllBytes(fileName); retmsg = "HTTP/0.9 200 OK" + CRLF; //retmsg += "Server: private_httpd" + CRLF; //retmsg += "Status: 200 OK" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; //retmsg += CRLF; break; default: retmsg = "HTTP/0.9 415 Unsupported Media Type" + CRLF; retmsg += "Server: private_httpd" + CRLF; retmsg += "Status: 415 Unsupported Media Type" + CRLF; retmsg += "Content-Length: " + retByte.Length.ToString() + CRLF; retmsg += "Connection: " + connect + CRLF; break; } } else { Console.WriteLine("'" + fileName + "'は存在しません。"); retmsg = "HTTP/0.9 404 Not Found" + CRLF; retmsg += "Server: private_httpd" + CRLF; retmsg += "Status: 404 Not Found" + CRLF; retmsg += "Connection: " + connect + CRLF; } if (connect == "Keep-Alive") { statusflag = true; } else { statusflag = false; } break; case "POST": /* HTTP/1.0 * GETとは反対にクライアントがサーバにデータを送信する。 * Webフォームや電子掲示板への投稿などで使用される。 * GETの場合と同じく、サーバはクライアントにデータを返すことができる。 */ case "PUT": /* HTTP/1.0 201 Created 202 Accepted * 指定したURIにリソースを保存する。 * URIが指し示すリソースが存在しない場合は、サーバはそのURIにリソースを作成する。 * 画像のアップロードなどが代表的。 */ case "HEAD": /* HTTP/1.0 200 OK * GETと似ているが、サーバはHTTPヘッダのみ返す。 * クライアントはWebページを取得せずともそのWebページが存在するかどうかを知ることができる。 * 例えばWebページのリンク先が生きているか、データを全て取得することなく検証することができる */ case "DELETE": // HTTP/1.0 指定したURIのリソースを削除する case "OPTIONS": // HTTP/1.1 サーバを調査する。例えば、サーバがサポートしているHTTPバージョンなどを知ることができる。 case "TRACE": /* HTTP/1.1 * TRACEサーバまでのネットワーク経路をチェックする。 * サーバは受け取ったメッセージのそれ自体をレスポンスのデータにコピーして応答する。 * WindowsのTracertやUNIXのTracerouteとよく似た動作。 */ case "CONNECT": /* HTTP/1.1 * TRACEサーバまでのネットワーク経路をチェックする。サーバは受け取ったメッセージのそれ自体をレスポンスのデータにコピーして応答する。 * WindowsのTracertやUNIXのTracerouteとよく似た動作。CONNECTTCPトンネルを接続する。 * 暗号化したメッセージをプロキシサーバを経由して転送する際に用いる。 */ retmsg = "HTTP/0.9 501 Not Implemented\n\n"; statusflag = false; break; default: retmsg = "HTTP/0.9 400 Bad Request\n\n"; statusflag = false; break; } //true:接続継続 false:接続終了 return(statusflag); }
public StringWriterWithEncoding(System.Text.StringBuilder sb) : base(sb) { this.encoding = System.Text.Encoding.Unicode; }
public ANTLRFileStream(string fileName, Encoding encoding) { this.fileName = fileName; Load(fileName, encoding); }
private static sbyte[] GetSBytesForEncoding(System.Text.Encoding encoding, string s) { sbyte[] sbytes = new sbyte[encoding.GetByteCount(s)]; encoding.GetBytes(s, 0, s.Length, (byte[])(object)sbytes, 0); return(sbytes); }
public NetworkReader(Stream _input, System.Text.Encoding _encoding) : base(_input, _encoding) { }
public void AppendAllLines(string path, IEnumerable <string> contents, System.Text.Encoding encoding) => System.IO.File.AppendAllLines(path, contents, encoding);
public File(string gameName, string path, string changesFolder, System.Text.Encoding encoding) : base(gameName, path, changesFolder, encoding) { }
// de https://stackoverflow.com/questions/40090098/deserialize-xml-where-string-may-contain-xml-html static void Main(string[] args) { Console.WriteLine("03_Tubo_Read_TMX_ME (c) 2021 mcanals MIT License"); bool commandlineerrors = false; string inpfileORI = "none"; int splitsize = 0; if (args.Length == 2) { inpfileORI = args[0].Trim(); if (!File.Exists(inpfileORI)) { Console.WriteLine("Looks like TMX file '{0}' does not exist", inpfileORI); commandlineerrors = true; } else { if (inpfileORI.Length > 4) { if (inpfileORI.Substring(inpfileORI.Length - 4).ToUpper() != ".TMX") { Console.WriteLine("Looks like TMX file '{0}' has not a valid name (must end with '.TMX')", inpfileORI); commandlineerrors = true; } } else { // less than 4 chars Console.WriteLine("Looks like TMX file '{0}' has not a valid name (should be at least 5 char filename as 'n.TMX')", inpfileORI); commandlineerrors = true; } } // now the number if (!int.TryParse(args[1], out splitsize)) { Console.WriteLine("Cannot convert '{0}' to an int", args[1]); commandlineerrors = true; } } else { Console.WriteLine("You need to specify 2 parameters. Number of detected parameters is '{0}'", args.Length); commandlineerrors = true; } if (commandlineerrors) { Console.WriteLine("Format or input not valid. Correct format: "); Console.WriteLine("03_Tubo_READ_TMX_MEM path\\file.TMX integer_number_to_split"); return; } Console.WriteLine("File -> {0}", inpfileORI); Console.WriteLine("Split -> {0}", splitsize); // instead of directly serialize we need to use XMLWriter settins // otherwise origina CR/LF in CDTA will be converted in LF // as this is the default behaivor for XML // https://stackoverflow.com/questions/60976792/net-core-3-1-soap-platform-not-supported-error-compiling-jscript-csharp-script XmlSerializer ser = new XmlSerializer(typeof(tmx)); XmlWriterSettings x_settings = new XmlWriterSettings(); // x_settings.NewLineChars = Environment.NewLine; // x_settings.NewLineOnAttributes = true; // x_settings.NewLineHandling = NewLineHandling.Replace; // x_settings.CloseOutput = true; x_settings.Indent = true; // this is what we need // x_settings.NewLineHandling = NewLineHandling.Entitize; // x_settings.NewLineOnAttributes = true; XmlWriter x_write; // inpfileORI = @"C:\u\usr\pro\VS2019\test\00_data\TEST.TMX"; //inpfileORI = @"C:\u\usr\pro\VS2019\test\00_data\MFP20ABD030_SPA.TMX"; //inpfileORI = @"C:\u\usr\pro\VS2019\test\00_data\_ABD004.TMX"; //inpfileORI = @"C:\u\usr\pro\VS2019\test\00_data\LEGAL_UTF-8.TMX"; string inpfile = inpfileORI.Replace(".TMX", "_CDATA.TMX"); // inpfile = @"C:\u\usr\pro\VS2019\test\00_data\BM150ABD005_SPA.TMX"; // me he quedado aquí. El problema es que los TMX contienen tags <ph> que // no son válidos en un xml y la serialización falla. La solución es poner // un evento que se desencandena cuando encuentra un elemento desconocido // (desonocido pq lo quitamos de la definición de la clase). De esa manera // he conseguido leer los tags. El problema es que al serializar de nuevo // como no son válidos me los resuelve a la hora de escribir la nueva clasa // la solución creo más correcta es preprocesar el tmx para qu sea cdata // pero es pues un apaño y ya no quiero perder más tiempo. // Además los tmx cambian la traducción. // me he quedado pues en el preproceso string line = ""; bool insideCDATA = false; // we need to read the encoding of the TMX file (otherwise // serailization will fail System.Text.Encoding encoding = System.Text.Encoding.UTF8; using (var reader = new StreamReader(inpfileORI)) { while ((line = reader.ReadLine()) != null) { string auxS = line.ToUpper(); if (auxS.Contains("UTF-16")) { encoding = System.Text.Encoding.Unicode; } break; } } x_settings.Encoding = encoding; using (StreamWriter writer = new StreamWriter(inpfile, false, encoding)) { using (var reader = new StreamReader(inpfileORI, encoding)) { while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (insideCDATA == false) { // not in CDDATA string iniseg = "<seg>"; string iniCDATA = "<![CDATA["; string auxlin = line.TrimStart(); if (auxlin.Length >= iniseg.Length) // at least <seg> lenght { if (iniseg == auxlin.Substring(0, iniseg.Length)) { // found segment but before doing it lets make // sure no CDATA is already there bool ContainsCDATA = false; if (auxlin.Length > iniseg.Length + "[CDATA[".Length) { ; ContainsCDATA = auxlin.Contains("[CDATA["); } // we cannot add CDATA if already exists if (ContainsCDATA == false) // we can add { line = line.Replace(iniseg, iniseg + iniCDATA); insideCDATA = true; // inside CDTA } } } } if (insideCDATA == true) // we have to close CDTA { string auxlin = line.TrimStart(); string finseg = "</seg>"; string finCDATA = "]]>"; if (auxlin.Length >= finseg.Length) // min lenght { if (finseg == auxlin.Substring(auxlin.Length - finseg.Length)) { // encontrado line = line.Replace(finseg, finCDATA + finseg); insideCDATA = false; } } } writer.WriteLine(line); } } } string outfile = inpfile.Replace("_CDATA.TMX", "_CDATA_{0}.TMX"); // tmx myTMX = ser.Deserialize(new FileStream(inpfile, FileMode.Open,FileAccess.Read, FileShare.Read)) as tmx; tmx myTMX; using (Stream stream = new FileStream(inpfile, FileMode.Open, FileAccess.Read, FileShare.Read)) { myTMX = (tmx)ser.Deserialize(stream); } int recordtotal = 0; int recordsplit = -1; int record = -1; List <String> Splittedfiles = new List <String>(); if (myTMX != null) { Console.WriteLine("TMX file {0} is valid", inpfile); } tmx myOutTMX = ser.Deserialize(new FileStream(inpfile, FileMode.Open, FileAccess.Read, FileShare.Read)) as tmx; recordtotal = myTMX.body.GetLength(0) - 1; // first dimension number of items var splitlist = new List <tmxTU>(); while (record < recordtotal) { // new record record += 1; recordsplit += 1; splitlist.Add(myTMX.body[record]); if (recordsplit >= splitsize - 1) { // flush myOutTMX.body = splitlist.ToArray(); using (Stream stream = new FileStream(string.Format(outfile, record + 1), FileMode.Create, FileAccess.Write)) { // ser.Serialize(stream, myOutTMX); x_write = XmlWriter.Create(stream, x_settings); ser.Serialize(x_write, myOutTMX); x_write.Close(); } // this only closses at the end. //ser.Serialize(new FileStream(string.Format(outfile, record + 1), FileMode.Create, FileAccess.Write), myOutTMX); splitlist = new List <tmxTU>(); recordsplit = -1; Splittedfiles.Add(string.Format(outfile, record + 1)); } } if (recordsplit != -1) { // final chunk as records myOutTMX.body = splitlist.ToArray(); using (Stream stream = new FileStream(string.Format(outfile, record + 1), FileMode.Create, FileAccess.Write)) { // ser.Serialize(stream, myOutTMX); x_write = XmlWriter.Create(stream, x_settings); ser.Serialize(x_write, myOutTMX); x_write.Close(); } Splittedfiles.Add(string.Format(outfile, record + 1)); // ser.Serialize(new FileStream(string.Format(outfile, record+1), FileMode.Create, FileAccess.Write), myOutTMX); } // final conversion foreach (string SplittedCDATAfile in Splittedfiles) { // like C:\u\usr\pro\VS2019\test\00_data\_ABD004_CDATA_2029.TMX string Splittedfile = SplittedCDATAfile.Replace("_CDATA", ""); // need to read CDATA and Write removing CDATA using (var writer = new StreamWriter(Splittedfile)) { using (var reader = new StreamReader(SplittedCDATAfile)) { while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (insideCDATA == false) { // not in CDDATA string iniseg = "<seg><![CDATA["; string newiniseg = "<seg>"; string auxlin = line.TrimStart(); if (auxlin.Length >= iniseg.Length) // at least <seg><![CDATA[ lenght { if (iniseg == auxlin.Substring(0, iniseg.Length)) { line = line.Replace(iniseg, newiniseg); insideCDATA = true; // inside CDTA } } } if (insideCDATA == true) // we have to close CDTA { string auxlin = line.TrimStart(); string finseg = "]]></seg>"; string newfinseg = "</seg>"; if (auxlin.Length >= finseg.Length) // min lenght { if (finseg == auxlin.Substring(auxlin.Length - finseg.Length)) { // encontrado line = line.Replace(finseg, newfinseg); insideCDATA = false; } } } writer.WriteLine(line); } } } } Console.WriteLine("EOP!"); }
/// <summary> /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>. /// </summary> /// <param name='p_id'> /// Identificador único do arquivo ou diretório (se aplicável). /// </param> /// <param name='p_parentid'> /// Identificador do diretório pai do arquivo ou diretório (se aplicável). /// </param> /// <param name='p_type'> /// Indica se é um arquivo ou um diretório. /// </param> /// <param name='p_completename'> /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual. /// </param> /// <param name='p_lastwritedate'> /// Data da última modificação do arquivo ou diretório. /// </param> /// <param name='p_size'> /// Tamanho do arquivo. /// </param> public File(int p_id, int p_parentid, Spartacus.Utils.FileType p_type, string p_completename, System.DateTime p_lastwritedate, long p_size) { this.v_id = p_id; this.v_parentid = p_parentid; this.v_filetype = p_type; this.v_pathseparator = Spartacus.Utils.PathSeparator.SLASH; this.v_name = this.GetBaseName(p_completename); this.v_extension = this.GetExtension(p_completename); this.v_path = this.GetPath(p_completename); this.v_lastwritedate = p_lastwritedate; this.v_size = p_size; this.v_encoding = System.Text.Encoding.GetEncoding("utf-8"); this.v_protected = false; this.v_hidden = this.GetHidden(); }
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) { return(base.Json(data, contentType, contentEncoding, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>. /// </summary> /// <param name='p_type'> /// Indica se é um arquivo ou um diretório. /// </param> /// <param name='p_completename'> /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual. /// </param> /// <param name='p_separator'> /// Separador de diretórios do caminho completo do arquivo. /// </param> /// <param name='p_lastwritedate'> /// Data da última modificação do arquivo ou diretório. /// </param> /// <param name='p_size'> /// Tamanho do arquivo. /// </param> /// <param name='p_encoding'> /// Codificação do arquivo. /// </param> public File(Spartacus.Utils.FileType p_type, string p_completename, Spartacus.Utils.PathSeparator p_separator, System.DateTime p_lastwritedate, long p_size, System.Text.Encoding p_encoding) { this.v_filetype = p_type; this.v_pathseparator = p_separator; this.v_name = this.GetBaseName(p_completename); this.v_extension = this.GetExtension(p_completename); this.v_path = this.GetPath(p_completename); this.v_lastwritedate = p_lastwritedate; this.v_size = p_size; this.v_encoding = p_encoding; this.v_protected = false; this.v_hidden = this.GetHidden(); }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding) { }
/// <summary> /// Inicializa uma nova instância da classe <see cref="Spartacus.Utils.File"/>. /// </summary> /// <param name='p_type'> /// Indica se é um arquivo ou um diretório. /// </param> /// <param name='p_completename'> /// Nome completo, absoluto ou relativo, do arquivo ou diretório atual. /// </param> /// <param name='p_encryptedname'> /// Se o nome do arquivo está criptografado ou não. /// </param> /// <param name='p_lastwritedate'> /// Data da última modificação do arquivo ou diretório. /// </param> /// <param name='p_size'> /// Tamanho do arquivo. /// </param> /// <param name='p_encoding'> /// Codificação do arquivo. /// </param> public File(Spartacus.Utils.FileType p_type, string p_completename, bool p_encryptedname, System.DateTime p_lastwritedate, long p_size, System.Text.Encoding p_encoding) { Spartacus.Utils.Cryptor v_cryptor; string v_completename; if (p_encryptedname) { try { v_cryptor = new Spartacus.Utils.Cryptor("spartacus"); v_completename = v_cryptor.Decrypt(p_completename); } catch (System.Exception) { v_completename = p_completename; } } else v_completename = p_completename; this.v_filetype = p_type; this.v_pathseparator = Spartacus.Utils.PathSeparator.SLASH; this.v_name = this.GetBaseName(v_completename); this.v_extension = this.GetExtension(v_completename); this.v_path = this.GetPath(v_completename); this.v_lastwritedate = p_lastwritedate; this.v_size = p_size; this.v_encoding = p_encoding; this.v_protected = false; this.v_hidden = this.GetHidden(); }
public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding, bool leaveOpen) { }
/// <exception cref="System.IO.IOException"></exception> public AntlrFileStream(string fileName, Encoding encoding) { this.fileName = fileName; Load(fileName, encoding); }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding) { }
public TemplateGroupFile(string fullyQualifiedFileName, Encoding encoding) : this(fullyQualifiedFileName, encoding, '<', '>') { }
public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding, bool leaveOpen) { }
public TemplateGroupFile(Uri url, Encoding encoding, char delimiterStartChar, char delimiterStopChar) : base(delimiterStartChar, delimiterStopChar) { if (url == null) throw new ArgumentNullException("url"); if (encoding == null) throw new ArgumentNullException("encoding"); this._url = url; this.Encoding = encoding; this._fileName = _url.AbsolutePath; }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { }
public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding) { }
private static StreamWriter WriteInit(string directory) { System.Text.Encoding encode = System.Text.Encoding.GetEncoding("UTF-8"); return(new StreamWriter(Utilities.String.LogFilename(directory), true, encode)); }