public FileReverseReader(string path) { disposed = false; file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); encoding = FindEncoding(file); SetupCharacterStartDetector(); }
public SocketServer(int port, ErrorLogger errorLog, FileLogger debugLog) : base(errorLog, debugLog) { try { this.encoding = Encoding.ASCII; this.port = port; this.clients = new List<SocketClient>(); this.listenerLoopThread = new Thread(this.ListenerLoop); this.listenerLoopThread.IsBackground = true; this.listenerLoopThread.Start(); this.clientsLoopThread = new Thread(this.ClientsLoop); this.clientsLoopThread.IsBackground = true; this.clientsLoopThread.Start(); this.Store("Host.Version", AssemblyInfo.SarVersion); this.Store("Host.Port", this.port.ToString()); this.Store("Host.Clients", this.clients.Count.ToString()); this.Store("Host.Application.Product", AssemblyInfo.Product); this.Store("Host.Application.Version", AssemblyInfo.Version); } catch (Exception ex) { this.Log(ex); } }
private static void TestSingleEncoding(string text, int bufferSize, Encoding encoding) { DisposeCheckingMemoryStream stream = new DisposeCheckingMemoryStream(encoding.GetBytes(text)); var reader = new ReverseLineReader(() => stream, encoding, bufferSize); AssertLines(new LineReader(() => new StringReader(text)).Reverse(), reader); Assert.IsTrue(stream.Disposed); }
public SourceText CreateText(Stream stream, Encoding defaultEncoding, CancellationToken cancellationToken = default(CancellationToken)) { // this API is for a case where user wants us to figure out encoding from the given stream. // if defaultEncoding is given, we will use it if we couldn't figure out encoding used in the stream ourselves. Debug.Assert(stream != null); Debug.Assert(stream.CanSeek); Debug.Assert(stream.CanRead); if (defaultEncoding == null) { // Try UTF-8 try { return CreateTextInternal(stream, s_throwingUtf8Encoding, cancellationToken); } catch (DecoderFallbackException) { // Try Encoding.Default defaultEncoding = Encoding.Default; } } try { return CreateTextInternal(stream, defaultEncoding, cancellationToken); } catch (DecoderFallbackException) { return null; } }
private static void RunTests(Encoding enc, params string[] pathElements) { var engine = new FileHelperEngine<CustomersVerticalBar>(); engine.Encoding = enc; Assert.AreEqual(enc, engine.Encoding); CoreRunTest(engine, pathElements); }
public void AddFile(string directory, FtpItem item, string text, Encoding encoding) { var uri = GetUri(directory, item.Name); var data = encoding.GetBytes(text); item.Length = data.Length; if (_dict.ContainsKey(uri)) { _dict[uri] = data; } else { _dict.Add(uri, data); } if (_uri_ftpitem.ContainsKey(uri)) { _uri_ftpitem[uri] = item; } else { _uri_ftpitem.Add(uri, item); } }
/// <summary> /// 使用Get方法获取字符串结果(加入Cookie) /// </summary> /// <param name="url"></param> /// <param name="cookieContainer"></param> /// <param name="encoding"></param> /// <returns></returns> public static string HttpGet(string url, CookieContainer cookieContainer = null, Encoding encoding = null, int timeOut = App.AppRequestTimeOut) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeOut; if (cookieContainer != null) { request.CookieContainer = cookieContainer; } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (cookieContainer != null) { response.Cookies = cookieContainer.GetCookies(response.ResponseUri); } using (Stream responseStream = response.GetResponseStream()) { using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8"))) { string retString = myStreamReader.ReadToEnd(); return retString; } } }
// Change character encoding of specified string. internal static string ChangeEncoding(this string value, Encoding currentEncoding, Encoding newEncoding) { if (newEncoding == null) return value; var buffer = currentEncoding.GetBytes(value); return newEncoding.GetString(buffer, 0, buffer.Length); }
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { _stream = stream; _ownsStream = ownsStream; _offset = 0; _encoding = encoding; }
/// <summary> /// Initializes a new instance of the <see cref="DownloadSecondaryServerVisitor"/> class. /// </summary> /// <param name="encoding">The encoding used to read and write strings.</param> public DownloadSecondaryServerVisitor(Encoding encoding) { // You should use an IoC container to do this. TcpReaderFactory = new TcpReaderFactory(); CurrentEncoding = encoding; }
public static String encode(String s, Encoding encoding) { if (s == null) return null; StringBuilder builder = new StringBuilder(); int start = -1; for (int i = 0; i < s.Length; i++) { char ch = s[i]; if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9' || " .-*_".IndexOf(ch) > -1)) { if (start >= 0) { convert(s.Substring(start, i - start), builder, encoding); start = -1; } if (ch != ' ') builder.Append(ch); else builder.Append('+'); } else { if (start < 0) start = i; } } if (start >= 0) convert(s.Substring(start, s.Length - start), builder, encoding); return builder.ToString().Trim().Replace("+", "%20").Replace("*", "%2A").Replace("%2F", "/"); }
public GitWrapper(string outputDirectory, Logger logger, Encoding commitEncoding, bool forceAnnotatedTags) : base(outputDirectory, logger, gitExecutable, gitMetaDir) { this.commitEncoding = commitEncoding; this.forceAnnotatedTags = forceAnnotatedTags; }
protected void Arrange() { var random = new Random(); _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture); _operationTimeout = TimeSpan.FromSeconds(30); _encoding = Encoding.UTF8; _disconnectedRegister = new List<EventArgs>(); _errorOccurredRegister = new List<ExceptionEventArgs>(); _channelDataEventArgs = new ChannelDataEventArgs( (uint)random.Next(0, int.MaxValue), new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) }); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _channelMock = new Mock<IChannelSession>(MockBehavior.Strict); _sequence = new MockSequence(); _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); _channelMock.InSequence(_sequence).Setup(p => p.Open()); _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, _subsystemName, _operationTimeout, _encoding); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); }
/// <summary> /// /// </summary> /// <param name="fileName">文件名,包括文件路径</param> /// <param name="encoding">文件编码</param> public CsvStreamReader(string fileName, Encoding encoding) { this.rowAL = new ArrayList(); this.fileName = fileName; this.encoding = encoding; LoadCsvFile(); }
public EdifactWriter(Stream stream, Encoding encoding, EdifactCharacterSet edifactCharacterSet, char replacementCharacter, bool normalize = true) : base(stream, encoding) { this._fallbackChar = replacementCharacter; this._edifactCharacterSet = edifactCharacterSet; this._normalize = normalize; }
/// <summary> /// /// </summary> /// <param name="fileName">文件名,包括文件路径</param> public CsvStreamReader(string fileName) { this.rowAL = new ArrayList(); this.fileName = fileName; this.encoding = Encoding.Default; LoadCsvFile(); }
/// <summary> /// Reads an <see cref="HttpWebResponse"/> as plain text. /// </summary> /// <param name="webResponse"> /// The <see cref="HttpWebResponse"/> to read. /// </param> /// <param name="encoding"> /// The encoding to be used. If omitted, the encoding specified in the web response shall be used. /// </param> /// <returns> /// A <see cref="string"/> that represents the text of an <see cref="HttpWebResponse"/>. /// </returns> public static string GetResponseText( this HttpWebResponse webResponse, Encoding encoding = null ) { if ( encoding == null ) { encoding = webResponse.GetEncoding(); } var s = webResponse.GetResponseStream(); if ( s != null ) { StreamReader sr; if ( webResponse.Headers[HttpResponseHeader.ContentEncoding] == "gzip" ) { sr = new StreamReader( new GZipStream( s, CompressionMode.Decompress ), encoding ); } else { sr = new StreamReader( s, encoding ); } var content = sr.ReadToEnd(); sr.Dispose(); return content; } return null; }
public StatVfsRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, Action<SftpExtendedReplyResponse> extendedAction, Action<SftpStatusResponse> statusAction) : base(protocolVersion, requestId, statusAction, "*****@*****.**") { Encoding = encoding; Path = path; SetAction(extendedAction); }
/// <summary> /// 获取远程信息 /// </summary> /// <param name="url">请求地址</param> /// <param name="encoding">请求编码</param> /// <param name="wc">客户端</param> public static string Get(string url, Encoding encoding = null, WebClient wc = null) { if (string.IsNullOrWhiteSpace(url)) { return string.Empty; } url = url.Replace("\\", "/"); if (encoding == null) encoding = Encoding.UTF8; var isNew = wc == null; if (wc == null) { wc = new WebClient(); wc.Proxy = null; wc.Headers.Add("Accept", "*/*"); wc.Headers.Add("Referer", url); wc.Headers.Add("Cookie", "bid=\"YObnALe98pw\";"); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.5 Safari/537.31"); } string strResult = null; try { var data = wc.DownloadData(url); strResult = encoding.GetString(data); } catch { return string.Empty; } finally { if (!isNew) Cookies(wc); if (isNew) wc.Dispose(); } return strResult; }
public static BinaryWriter GetBinaryWriter(this byte[] data, Encoding encoding = null) { Contract.Requires(data != null); Contract.Ensures(Contract.Result<BinaryWriter>() != null); return new BinaryWriter(new MemoryStream(data), encoding ?? Encoding.UTF8); }
public void LoadFrom( string filepath, Encoding encoding ) { //todo thread this operation may take a lot of time and make it look cool when it loads listText.Clear(); InsertRange( 0, File.ReadLines( filepath, encoding ) ); modified = false; }
private static void RunAsyncConstructor(Encoding enc, params string[] pathElements) { var asyncEngine = new FileHelperAsyncEngine<CustomersVerticalBar>(enc); Assert.AreEqual(enc, asyncEngine.Encoding); CoreRunAsync(asyncEngine, pathElements); }
public SftpOpenDirRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, Action<SftpHandleResponse> handleAction, Action<SftpStatusResponse> statusAction) : base(protocolVersion, requestId, statusAction) { this.Path = path; this.Encoding = encoding; this.SetAction(handleAction); }
public CommonVolumeDescriptor(byte[] src, int offset, Encoding enc) : base(src, offset) { CharacterEncoding = enc; SystemIdentifier = IsoUtilities.ReadChars(src, offset + 8, 32, CharacterEncoding); VolumeIdentifier = IsoUtilities.ReadChars(src, offset + 40, 32, CharacterEncoding); VolumeSpaceSize = IsoUtilities.ToUInt32FromBoth(src, offset + 80); VolumeSetSize = IsoUtilities.ToUInt16FromBoth(src, offset + 120); VolumeSequenceNumber = IsoUtilities.ToUInt16FromBoth(src, offset + 124); LogicalBlockSize = IsoUtilities.ToUInt16FromBoth(src, offset + 128); PathTableSize = IsoUtilities.ToUInt32FromBoth(src, offset + 132); TypeLPathTableLocation = Utilities.ToUInt32LittleEndian(src, offset + 140); OptionalTypeLPathTableLocation = Utilities.ToUInt32LittleEndian(src, offset + 144); TypeMPathTableLocation = Utilities.BitSwap(Utilities.ToUInt32LittleEndian(src, offset + 148)); OptionalTypeMPathTableLocation = Utilities.BitSwap(Utilities.ToUInt32LittleEndian(src, offset + 152)); DirectoryRecord.ReadFrom(src, offset + 156, CharacterEncoding, out RootDirectory); VolumeSetIdentifier = IsoUtilities.ReadChars(src, offset + 190, 318 - 190, CharacterEncoding); PublisherIdentifier = IsoUtilities.ReadChars(src, offset + 318, 446 - 318, CharacterEncoding); DataPreparerIdentifier = IsoUtilities.ReadChars(src, offset + 446, 574 - 446, CharacterEncoding); ApplicationIdentifier = IsoUtilities.ReadChars(src, offset + 574, 702 - 574, CharacterEncoding); CopyrightFileIdentifier = IsoUtilities.ReadChars(src, offset + 702, 739 - 702, CharacterEncoding); AbstractFileIdentifier = IsoUtilities.ReadChars(src, offset + 739, 776 - 739, CharacterEncoding); BibliographicFileIdentifier = IsoUtilities.ReadChars(src, offset + 776, 813 - 776, CharacterEncoding); CreationDateAndTime = IsoUtilities.ToDateTimeFromVolumeDescriptorTime(src, offset + 813); ModificationDateAndTime = IsoUtilities.ToDateTimeFromVolumeDescriptorTime(src, offset + 830); ExpirationDateAndTime = IsoUtilities.ToDateTimeFromVolumeDescriptorTime(src, offset + 847); EffectiveDateAndTime = IsoUtilities.ToDateTimeFromVolumeDescriptorTime(src, offset + 864); FileStructureVersion = src[offset + 881]; }
private void CheckOutput(IProjectFile projectFile, Encoding encoding) { Assert.IsNotNull(projectFile, "projectFile == null"); this.ExecuteWithGold( projectFile.Location.Name, sw => { using (var sr = new StreamReader(projectFile.Location.OpenFileForReadingExclusive(), encoding, true)) { var lexer = this.CreateLexer(projectFile, sr); int position = 0; lexer.Start(); while (lexer.TokenType != null) { Assert.AreEqual( lexer.TokenStart, position, "Token start error. Expected: {0}, actual: {1}", position, lexer.TokenStart); position = lexer.TokenEnd; this.WriteToken(sw, lexer); lexer.Advance(); } Assert.AreEqual(lexer.Buffer.Length, position, "position == lexer.Buffer.Length"); } }); }
/// <summary> /// 新しいこのクラスのインスタンスを構築します。 /// </summary> /// <param name="sourcePath">比較元ファイルパス</param> /// <param name="destinationPath">比較先ファイルパス</param> /// <param name="encode">ファイルのエンコード</param> public TextFileMarger(string sourcePath, string destinationPath, Encoding encode) : base() { SourcePath = sourcePath; DestinationPath = destinationPath; Encoding = encode; }
public StructureSegment(byte[] pBuffer, int pStart, int pLength, byte locale) { mBuffer = new byte[pLength]; try { switch (locale) { case MapleLocale.KOREA: case MapleLocale.KOREA_TEST: encoding = Encoding.GetEncoding(51949); // EUC_KR break; case MapleLocale.JAPAN: encoding = Encoding.GetEncoding(50222); // Shift_JIS break; case MapleLocale.CHINA: encoding = Encoding.GetEncoding(54936); // GB18030 break; case MapleLocale.TESPIA: encoding = Encoding.Default; break; case MapleLocale.TAIWAN: encoding = Encoding.GetEncoding("BIG5-HKSCS"); break; default: encoding = Encoding.UTF8; break; } } catch { encoding = Encoding.UTF8; } Buffer.BlockCopy(pBuffer, pStart, mBuffer, 0, pLength); }
/// <include file='doc\XmlParserContext.uex' path='docs/doc[@for="XmlParserContext.XmlParserContext3"]/*' /> public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, String docTypeName, String pubId, String sysId, String internalSubset, String baseURI, String xmlLang, XmlSpace xmlSpace, Encoding enc) { if (nsMgr != null) { if (nt == null) { _nt = nsMgr.NameTable; } else { if ( (object)nt != (object) nsMgr.NameTable ) { throw new XmlException(Res.Xml_NotSameNametable); } _nt = nt; } } else { _nt = nt; } _nsMgr = nsMgr; _docTypeName = (null == docTypeName ? String.Empty : docTypeName); _pubId = (null == pubId ? String.Empty : pubId); _sysId = (null == sysId ? String.Empty : sysId); _internalSubset = (null == internalSubset ? String.Empty : internalSubset); _baseURI = (null == baseURI ? String.Empty : baseURI); _xmlLang = (null == xmlLang ? String.Empty : xmlLang); _xmlSpace = xmlSpace; _encoding = enc; }
public static IBlobSerializer AsBlobSerializer(this ITextSerializer serializer, Encoding encoding = null) { return new BlobSerializerDelegate( obj => serializer.SerializeToBytes(obj, encoding), (data, type) => serializer.DeserializeFromBytes(data, type, encoding), serializer.CanDeserialize); }
static void Main(string[] args) { encoding = Encoding.ASCII; SocketServer server; server = new SocketServer(new IPEndPoint(IPAddress.Loopback, 0)); server.Connected += c => { serverClient = new FramedClient(c); // When received is called, bs will contain no more and no less // data than whole packet as sent from client. serverClient.Received += bs => { var msg = encoding.GetString(bs.Array, bs.Offset, bs.Count); msg = "Hello, " + msg + "!"; serverClient.SendPacket(encoding.GetBytes(msg)); }; }; server.Start(); HandleClient(server.BindEndPoint.Port); Console.WriteLine("Press any key to stop..."); Console.ReadKey(); server.Stop(); client.Close(); serverClient.Close(); }
/// <summary> /// SHA1 加密,返回大写字符串 /// </summary> /// <param name="content">需要加密字符串</param> /// <param name="encode">指定加密编码</param> /// <returns>返回40位大写字符串</returns> public static string SHA1_Encrypt(this string toEncryptString, Text.Encoding encoding = null) { if (encoding == null) { encoding = Text.Encoding.UTF8; } return(Util.Cryptography.SHA1Utils.Encrypt(toEncryptString, encoding)); }
} // Nothing to do /// <summary> /// Initializes this instance of EndianAwareBinaryReader with the given input stream, /// the given text encoding, and the Endianness of the given DataConverter /// </summary> /// <param name="output">The stream to read input From</param> /// <param name="encoding">The encoding to read text with</param> /// <param name="DataConverter">The DataConverter with the Endianness to use</param> public EndianAwareBinaryReader(System.IO.Stream output, System.Text.Encoding encoding, System.DataConverter DataConverter) : base(output, encoding) { this._DataConverter = DataConverter; this._ExplicitEncoding = this._AssumedEffectiveEncoding = encoding; }
/// <summary> /// 发送电子邮件函数 /// </summary> /// <param name="txtHost">电子邮件服务主机名称</param> /// <param name="txtFrom">发送人地志</param> /// <param name="txtPass">发信人密码</param> /// <param name="txtTo">收信人地址</param> /// <param name="txtSubject">邮件标题</param> /// <param name="txtBody">邮件内容</param> /// <param name="isBodyHtml">是否采用HTML编码</param> /// <param name="priority">电子邮件的优先级别</param> /// <param name="encoding">内容采用的编码方式</param> /// <param name="files">附件(可选填)</param> /// <returns>操作结果</returns> public static string SendMail(string txtHost, string txtFrom, string txtPass, string txtTo, string txtSubject, string txtBody, bool isBodyHtml, MailPriority priority, System.Text.Encoding encoding, params string[] files) { //电子邮件附件 Attachment data = null; //传送的电子邮件类 MailMessage message = new MailMessage(txtFrom, txtTo); //设置标题 message.Subject = txtSubject; //设置内容 message.Body = txtBody; //是否采用HTML编码 message.IsBodyHtml = isBodyHtml; //电子邮件的优先级别 message.Priority = priority; //内容采用的编码方式 message.BodyEncoding = encoding; try { //添加附件 if (files.Length > 0 && files != null) { for (int i = 0; i < files.Length; i++) { //实例话电子邮件附件,并设置类型 data = new Attachment(files[i], System.Net.Mime.MediaTypeNames.Application.Octet); //实例邮件内容 System.Net.Mime.ContentDisposition disposition = data.ContentDisposition; //取得建档日期 disposition.CreationDate = System.IO.File.GetCreationTime(files[i]); //取得附件修改日期 disposition.ModificationDate = System.IO.File.GetLastWriteTime(files[i]); //取得读取日期 disposition.ReadDate = System.IO.File.GetLastAccessTime(files[i]); //设定文件名称 System.IO.FileInfo fi = new System.IO.FileInfo(files[i]); disposition.FileName = fi.Name.ToString(); //添加附件 message.Attachments.Add(data); } } //实例从送电子邮件类 SmtpClient client = new SmtpClient(); //设置电子邮件主机名称 client.Host = txtHost; //取得寄信人认证 client.Credentials = new NetworkCredential(txtFrom, txtPass); //发送电子邮件 client.Send(message); return("OK"); } catch (Exception Err) { //返回错误信息 return(Err.Message); } finally { //销毁电子邮件附件 if (data != null) { data.Dispose(); } //销毁传送的电子邮件实例 message.Dispose(); } }
private static string MyMatchEvaluatorBase64(Match m) { System.Text.Encoding enc = System.Text.Encoding.UTF7; return(enc.GetString(Convert.FromBase64String(m.Groups[1].Value))); }
/// <summary> /// Récupération des données du fichiers « dataetclassif.txt » /// </summary> private void RecupererDonnees() { try { // Ouverture du fichier System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("iso-8859-1"); StreamReader Lecteur = new StreamReader("../../../ApprentissageData/datasetclassif.txt", encoding); // Initialisation des variables Observations = new List <Observation>(); string Donnee = Lecteur.ReadLine(); int Item = 2; List <double> Coordonnees = new List <double> { 0, 0 }; // Parcours de chaque ligne du fichier while (Donnee != null) { // Conversion du texte de la ligne lue en double double DonneeChiffree = Convert.ToDouble(Donnee); // Cas où la donnée est intéressante if (Item != 2) { Coordonnees[Item] = DonneeChiffree; Item++; } // Cas où la donnée est inintéressante else { Observations.Add(new Observation(Coordonnees[0], Coordonnees[1])); Coordonnees[0] = 0; Coordonnees[1] = 0; Item = 0; } // Passage à la ligne suivante Donnee = Lecteur.ReadLine(); } // Fermeture du fichier Lecteur.Close(); // Ajout de la dernière observation et retrait de la première Observations.Add(new Observation(Coordonnees[0], Coordonnees[1])); Observations.RemoveAt(0); // Mélange des observations int NbObservations = Observations.Count; ObservationsTriees.AddRange(Observations); List <Observation> ObservationsMelangees = new List <Observation>(); for (int i = 0; i < NbObservations; i++) { int Numero = Alea.Next(Observations.Count); ObservationsMelangees.Add(Observations[Numero]); Observations.RemoveAt(Numero); } Observations = ObservationsMelangees; } catch (Exception Ex) { string Erreur = "Une erreur est survenue au cours de l’opération :"; MessageBox.Show(Erreur + "\n" + Ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Initializes the production of an email message, creating its headers and main body. Note that this /// action does not immediately send the message, as you may want to add futher parts (attachments) to /// it (using <see cref="AddPart" />). To finalize message and send it you should then call RichMailSend /// </summary> /// <remarks> /// Older emails clients (such as some versions of Lotus and Outlook 2000) do not correctly support the MIME encoding used to send HTML emails. To enable HTML emails to be delivered correctly to these clients you can add "lotus/compatible" (without the quotes) to the ContentType. This will change how the whole email is created and allows those clients to shows the message properly at the expense of more recent email clients (such as Yahoo! Mail) that will not display the message correctly. /// </remarks> /// <param name="processAddresses">Pre-process the email addresses?</param> /// <param name="ssFrom">Email address of the sender</param> /// <param name="ssTo">Email addresses to send the email to (comma separated)</param> /// <param name="headers">Email header information</param> /// <param name="ssCc">Email addresses to carbon-copy the email to (comma separated)</param> /// <param name="ssBcc">Email addresses to blind carbon-copy the email to (comma separated)</param> /// <param name="ssContentType">MIME type of the message.</param> /// <param name="ssCharset">Character used in the message text</param> /// <param name="ssSubject">Subject of the message</param> /// <param name="ssBody">Text content of the message</param> /// <param name="ssBodyIsHtml">TRUE if content of the message is HTML rather than plain text</param> /// <param name="ssUrl">Base URL to use in case the Body is HTML. This allows any relative paths that may exist in the Body to be expanded to full blown URL's</param> /// <param name="ssIncludeImages">If TRUE, any images referenced via an URL in the Body are attached to the message</param> /// <param name="ssInReplyTo">Alternate reply-to email address</param> /// <param name="userAgent">User agent to use to request the email messages.</param> /// <param name="realHostname">The hostname to use when building links in the email body.</param> /// <param name="zoneAddress">Deploymentzoneadress of the running espace</param> /// <param name="ssBoundary">System marker that should be passed in to any further parts that are added to this message (see <see cref="AddPart" />).</param> /// <param name="ssMail">The full message text produced by the call</param> /// <param name="emailId">The created email id.</param> public static void CreateEmail(bool processAddresses, string ssFrom, string ssTo, List <String> headers, string ssCc, string ssBcc, string ssContentType, string ssCharset, string ssSubject, string ssBody, bool ssBodyIsHtml, string ssUrl, bool ssIncludeImages, string ssInReplyTo, string userAgent, string realHostname, string zoneAddress, out string ssBoundary, out string ssMail, out string emailId) { bool prepareMimeEncoding = true; //string base64 = null; bool use_multipart_related = true; ssBoundary = ""; System.Text.StringBuilder sbMail = new System.Text.StringBuilder(); if (realHostname == null) { throw new InvalidOperationException("The 'Default DNS Name' must be set in Service Center's Environment Configuration to send emails."); } // Cleanup the content type ssContentType = EmailHelper.TrimHeaderLine(ssContentType); // This is a hack to support Outlook 2000 and other clients // that do not support multipart/related. int tpos = ssContentType.ToUpper().IndexOf("LOTUS/COMPATIBLE"); if (tpos >= 0) { ssContentType = ssContentType.Remove(tpos, 16); use_multipart_related = false; } // If no Content Type defined, set it to "multipart/mixed" if (ssContentType == "") { ssContentType = "multipart/mixed"; } if (!ssContentType.ToLower().StartsWith("multipart")) { // If it's not a multipart message then don't encase in MIME containers prepareMimeEncoding = false; } if (ssBodyIsHtml) { prepareMimeEncoding = true; } // If no Content Type defined, set it to "multipart/mixed" if (ssCharset == "") { ssCharset = "iso-8859-1"; } else { ssCharset = EmailHelper.TrimHeaderLine(ssCharset); } // Get a correct encoder System.Text.Encoding mailEncoding = System.Text.Encoding.GetEncoding(ssCharset); if (prepareMimeEncoding) { // Get a random boundary ssBoundary = EmailHelper.CreateRandomBoundary(); } else { ssBoundary = ""; } // Add date to email header sbMail.Append("Date: "); sbMail.Append(EmailHelper.GetEmailDate(System.DateTime.Now)); sbMail.Append("\r\n"); if (processAddresses) { ssFrom = EmailHelper.ProcessEmailAddresses(mailEncoding, ssFrom); } emailId = System.Guid.NewGuid().ToString().Replace("-", "") + "@" + RuntimePlatformSettings.EMail.ServerHost.GetValue(); // Add the EmailID sbMail.Append("Message-ID: <" + emailId + ">\r\n"); // Add from to email header sbMail.Append("From: "); sbMail.Append(ssFrom); sbMail.Append("\r\n"); if (processAddresses) { // If any of the email addresses in the To field are in the format // "description <email address>", then encode with iso-8859-1 the description. ssTo = EmailHelper.ProcessEmailAddresses(mailEncoding, ssTo); } // Add to to email header sbMail.Append("To: "); sbMail.Append(ssTo); sbMail.Append("\r\n"); // Add headers if (headers != null) { foreach (String header in headers) { sbMail.Append(header); sbMail.Append("\r\n"); } } // If cc not empty, add it to email header if (ssCc != "") { if (processAddresses) { // If any of the email addresses in the Cc field are in the format // "description <email address>", then encode with iso-8859-1 the description. ssCc = EmailHelper.ProcessEmailAddresses(mailEncoding, ssCc); } // Add it to the email header sbMail.Append("Cc: "); sbMail.Append(ssCc); sbMail.Append("\r\n"); } ssInReplyTo = EmailHelper.TrimHeaderLine(ssInReplyTo); // Add In-Reply-To to email header if (ssInReplyTo != "") { sbMail.Append("In-Reply-To:"); sbMail.Append(ssInReplyTo); sbMail.Append("\r\n"); } ssSubject = EmailHelper.TrimHeaderLine(ssSubject); EncodeFlags headerEncodeFlags = EncodeFlags.SingleLine | EncodeFlags.QuotedPrintable; // Encode the subject if (EmailEncoding.NeedsEncoding(mailEncoding, ssSubject, headerEncodeFlags)) { ssSubject = EmailEncoding.EncodeString(mailEncoding, ssSubject, headerEncodeFlags); } // Add subject to email header sbMail.Append("Subject: "); sbMail.Append(ssSubject); sbMail.Append("\r\n"); // Add content type to email header if (prepareMimeEncoding) { sbMail.Append("MIME-Version: 1.0\r\n"); } if (prepareMimeEncoding) { sbMail.Append("Content-Type: " + ssContentType + "; boundary=\"" + ssBoundary + "\"\r\n"); } else { sbMail.Append("Content-Type: " + ssContentType + "; charset=\"" + ssCharset + "\"\r\n"); sbMail.Append("Content-Transfer-Encoding: base64\r\n"); } //sbMail += "Content-Transfer-Encoding: base64\r\n"; if (prepareMimeEncoding) { sbMail.Append("\r\n"); // For older clients to display something sbMail.Append("This is a multi-part message in MIME format.\r\n"); // Dump the starting boundary sbMail.Append("--" + ssBoundary + "\r\n"); } // Add body header to email //System.Text.Encoding bodyEncoding = System.Text.Encoding.GetEncoding(ssCharset); if (ssBodyIsHtml) { // Outlook 2000 is too old by now and treats emails using MULTIPART/RELATED as // MULTIPART/MIXED (which is standards compliant). // Thus if a tree like the following is used it will show an empty email // with two attachments. The first attachment is an email and a second one is the attachment file. // Begin Message // Begin Mixed Content // Begin Related Contnt // Begin Alternative Content // Plain text message // HTML Message message // End Alternative Content // Image // End Related Content // Attachment // End Mixed Content // End Message // // To avoid this we now have a flag that disables the use of MULTIPART/RELATED // and uses a tree like this : // Begin Message // Begin Mixed Content // Begin Alternative Content // Plain text message // HTML Message message // End Alternative Content // Image // Attachment // End Mixed Content // End Message string relatedBoundary = null; if (use_multipart_related) { relatedBoundary = EmailHelper.CreateRandomBoundary(); } string alternateBoundary = EmailHelper.CreateRandomBoundary(); string normBody; Hashtable uri2cidMap; StringCollection uris; // remove meta content type normBody = ScriptableEmailFunctions.GetRegex("<meta +http-equiv='?\"?content-type[^>]+>", RegexOptions.IgnoreCase).Replace(ssBody, ""); // Place stylesheet inline var match = ScriptableEmailFunctions.GetRegex("<link [^>]*href=\"([^\"]+\\.css)(\\?[0-9_]+)?\"[^>]*>", RegexOptions.IgnoreCase).Match(normBody); if (match.Success) { string css; Uri absUri = null; try { absUri = new Uri(new Uri(ssUrl), match.Groups[1].Value); } catch { } if (absUri != null) { string cssEncoding; EmailHelper.HttpGet(absUri.AbsoluteUri, MailUA, null, out css, out cssEncoding); css = EmailHelper.NormalizeCSS(css); normBody = normBody.Substring(0, match.Index) + "<style>" + css + "</style>" + normBody.Substring(match.Index + match.Length, normBody.Length - match.Index - match.Length); } } string returnBody; EmailHelper.HtmlProcessPaths(normBody, ssUrl, ssIncludeImages, use_multipart_related, out returnBody, out uris, out uri2cidMap); normBody = returnBody; // Replace localhost with the real name for any unescaped link that occurred (normal destinations are already ok) if (realHostname != null) //just for sanity check { normBody = ReplaceLinksWithEnvAddress(realHostname, zoneAddress, normBody); } string images = EmailHelper.HtmlFetchImages(ssIncludeImages, ssBoundary, use_multipart_related, relatedBoundary, uri2cidMap, userAgent); EmailHelper.HtmlAppendImages(ssCharset, EmailEncoding.MaxEncodedLength, use_multipart_related, sbMail, mailEncoding, relatedBoundary, alternateBoundary, normBody, images); } else if (ssBody != "") { if (prepareMimeEncoding) { sbMail.Append("Content-Type: text/plain; charset=\"" + ssCharset + "\"\r\n"); sbMail.Append("Content-Transfer-Encoding: base64\r\n"); } sbMail.Append("\r\n"); // Encode body and add it to the email sbMail.Append(EmailEncoding.GetBase64TextBlock(mailEncoding.GetBytes(ssBody), EmailEncoding.MaxEncodedLength)); } else { sbMail.Append("\r\n"); } ssMail = sbMail.ToString(); } // CreateEmail
public static string CreateLinkStringUrlencode(System.Collections.Generic.Dictionary <string, string> dicArray, System.Text.Encoding code) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); foreach (System.Collections.Generic.KeyValuePair <string, string> current in dicArray) { stringBuilder.Append(current.Key + "=" + System.Web.HttpUtility.UrlEncode(current.Value, code) + "&"); } int length = stringBuilder.Length; stringBuilder.Remove(length - 1, 1); return(stringBuilder.ToString()); }
public void Unicode_AddDirectoryByName_wi8984() { string format = "弹出应用程序{0:D3}.dir"; // Chinese characters System.Text.Encoding UTF8 = System.Text.Encoding.GetEncoding("UTF-8"); TestContext.WriteLine("== WorkItem 8984"); // three trials: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j = 0; j < 3; j++) { TestContext.WriteLine("Trial {0}", j); for (int n = 1; n <= 10; n++) { TestContext.WriteLine("nEntries {0}", n); var dirsAdded = new System.Collections.Generic.List <String>(); var zipFileToCreate = String.Format("wi8984-{0}-{1:N2}.zip", j, n); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { switch (j) { case 0: #pragma warning disable 618 zip1.UseUnicodeAsNecessary = true; #pragma warning restore 618 break; case 1: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.Always; break; } for (int i = 0; i < n; i++) { // create an arbitrary directory name, add it to the zip archive string dirName = String.Format(format, i); zip1.AddDirectoryByName(dirName); dirsAdded.Add(dirName + "/"); } zip1.Save(); } string extractDir = String.Format("extract-{0}-{1:D3}", j, n); int dirCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("dir: {0}", e.FileName); Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected entry ({0})", e.FileName); Assert.IsTrue(e.IsDirectory); e.Extract(extractDir); dirCount++; } } Assert.AreEqual <int>(n, dirCount); TestContext.WriteLine(""); } TestContext.WriteLine(""); } }
public void CodePage_UpdateZip_AlternateEncoding_wi10180() { System.Text.Encoding JIS = System.Text.Encoding.GetEncoding("shift_jis"); TestContext.WriteLine("The CP for JIS is: {0}", JIS.CodePage); ReadOptions options = new ReadOptions { Encoding = JIS }; string[] filenames = { "日本語.txt", "日本語テスト.txt" }; // three trials: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j = 0; j < 3; j++) { string zipFileToCreate = String.Format("wi10180-{0}.zip", j); // pass 1 - create it TestContext.WriteLine("Create zip, cycle {0}...", j); using (var zip = new ZipFile()) { switch (j) { case 0: #pragma warning disable 618 zip.ProvisionalAlternateEncoding = JIS; #pragma warning restore 618 break; case 1: zip.AlternateEncoding = JIS; zip.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip.AlternateEncoding = JIS; zip.AlternateEncodingUsage = ZipOption.Always; break; } zip.AddEntry(filenames[0], "This is the content for entry (" + filenames[0] + ")"); TestContext.WriteLine("adding file: {0}", filenames[0]); zip.Save(zipFileToCreate); } // pass 2 - read and update it TestContext.WriteLine("Update zip..."); using (var zip0 = ZipFile.Read(zipFileToCreate, options)) { foreach (var e in zip0) { TestContext.WriteLine("existing entry name: {0} encoding: {1}", e.FileName, e.AlternateEncoding.EncodingName); Assert.AreEqual <System.Text.Encoding> (options.Encoding, e.AlternateEncoding); } zip0.AddEntry(filenames[1], "This is more content..." + System.DateTime.UtcNow.ToString("G")); TestContext.WriteLine("adding file: {0}", filenames[1]); zip0.Save(); } // pass 3 - verify the filenames, again TestContext.WriteLine("Verify zip..."); using (var zip0 = ZipFile.Read(zipFileToCreate, options)) { foreach (string f in filenames) { Assert.AreEqual <string>(f, zip0[f].FileName, "The FileName was not expected, (cycle {0}) ", j); } } } }
//등록 자료 생성 public static string ConvertRegister(string path, string xmlZipcodeAreaPath, string xmlZipcodePath) { System.Text.Encoding _encoding = System.Text.Encoding.GetEncoding(strEncoding); //기본 인코딩 StreamReader _sr = null; //파일 읽기 스트림 StreamWriter _swError = null; StreamWriter _sw = null; byte[] _byteAry = null; string _strCode = ""; string _strLine = ""; string _strReturn = ""; string _col_gubun = ""; try { //파일 읽기 Stream과 오류시 저장할 쓰기 Stream 생성 _sr = new StreamReader(path, _encoding); _swError = new StreamWriter(path + ".Error", false, _encoding); while ((_strLine = _sr.ReadLine()) != null) { //2012.10.12 태희철 수정 _byteAry = _encoding.GetBytes(_strLine); _col_gubun = _encoding.GetString(_byteAry, 23, 1).Trim().ToUpper(); //_strCode = _encoding.GetString(_byteAry, 243, 6); //본인만배송건 if (_encoding.GetString(_byteAry, 44, 1) == "2") { _sw = new StreamWriter(path + ".긴급_본인만_6000", true, _encoding); _sw.WriteLine(_strLine + "0033104"); } else { _sw = new StreamWriter(path + ".긴급_5000", true, _encoding); _sw.WriteLine(_strLine + "0033102"); } //_sw.WriteLine(_strLine); _sw.Close(); } _strReturn = "성공"; } catch (Exception ex) { _strReturn = "실패"; if (_swError != null) { _swError.WriteLine(ex.Message); } } finally { if (_sr != null) { _sr.Close(); } if (_sw != null) { _sw.Close(); } if (_swError != null) { _swError.Close(); } } return(_strReturn); }
/// <summary> /// Reads information from WMAppManifest.xml. /// </summary> /// <returns></returns> public bool Read() { if (_fileName == null) { throw new Exception("File name is empty"); } UpdateView(); //Cleanup(); error = XapReadError.NotRead; string TempFileName = _fileName; bool deleteFile = false; IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); XDocument reader = null; StreamResourceInfo xapStream = null; try { if (TempFileName.Contains("\\")) { string shortname = _fileName.Substring(_fileName.LastIndexOf("\\") + 1).Replace("%20", " "); if (shortname.Contains(" ")) { bool res = Functions.CopyFile(_fileName, "\\Temp\\temp.xap"); if (res == false) { error = XapReadError.CouldNotCopyFile; throw new Exception("Could not copy file"); } TempFileName = "\\Temp\\temp.xap"; deleteFile = true; } } var uri = new Uri(TempFileName, UriKind.Relative); xapStream = Application.GetResourceStream(uri); if (xapStream == null) { error = XapReadError.OpenError; throw new Exception("Couldn't read XAP"); } _fileSize = xapStream.Stream.Length; // Input WMAppManifest not always has valid encoding. Let's try different ones to find the best. var stream = Application.GetResourceStream(xapStream, new Uri("WMAppManifest.xml", UriKind.Relative)).Stream; if (stream == null) { error = XapReadError.CouldNotOpenWMAppManifest; throw new Exception("Couldn't open WMAppManifest"); } byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); stream = null; var encodings = new System.Text.Encoding[3] { Encoding.UTF8, Encoding.Unicode, Encoding.BigEndianUnicode }; bool correctEncodingFound = false; for (int i = 0; i < encodings.Length; ++i) { try { Encoding enc = encodings[i]; string text = enc.GetString(bytes, 0, bytes.Length); text = text.Replace("utf-16", "utf-8"); byte[] newBytes = Encoding.UTF8.GetBytes(text); var memStream = new MemoryStream(newBytes); reader = XDocument.Load(memStream); memStream.Close(); memStream = null; } catch (Exception ex) { continue; } correctEncodingFound = true; break; } if (!correctEncodingFound) { error = XapReadError.InvalidEncoding; throw new Exception("Invalid WMAppManifest.xml encoding"); } } catch (Exception ex) { if (error == XapReadError.NotRead) { error = XapReadError.OpenError; } if (deleteFile == true) { Functions.RemoveFile(TempFileName); } UpdateView(); return(false); } _isSigned = false; try { var rs = Application.GetResourceStream(xapStream, new Uri("WMAppPRHeader.xml", UriKind.Relative)); if (rs != null) { _isSigned = true; rs.Stream.Close(); } } catch (Exception ex) { _isSigned = false; } var nodes = reader.Descendants().Descendants <XElement>(); bool AppNodeFound = false; bool ProductIdFound = false; foreach (var node in nodes) { string uri = node.BaseUri; if (node.Name.LocalName == "App") { AppNodeFound = true; var attrs = node.Attributes(); foreach (var attr in attrs) { switch (attr.Name.LocalName) { case "ProductID": _productId = attr.Value; ProductIdFound = true; break; case "Title": _title = attr.Value; break; case "Version": _version = attr.Value; break; case "Author": _author = attr.Value; break; case "Description": _description = attr.Value; break; case "Publisher": _publisher = attr.Value; break; case "Genre": _genre = attr.Value; break; } } _title = ExtractResourceString(xapStream, _title); _version = ExtractResourceString(xapStream, _version); _author = ExtractResourceString(xapStream, _author); _description = ExtractResourceString(xapStream, _description); _publisher = ExtractResourceString(xapStream, _publisher); var elems = node.Elements(); foreach (var elem in elems) { switch (elem.Name.LocalName) { case "IconPath": _applicationIcon = elem.Value; if (ExtractFile(xapStream, isf, _applicationIcon) == true) { string shortFileName = ShortenFileName(_applicationIcon); _applicationIcon = shortFileName; } break; case "Capabilities": var caps = elem.Elements(); foreach (var cap in caps) { Capabilities.Add(cap.Attribute("Name").Value); } break; } } } } xapStream.Stream.Close(); xapStream.Stream.Dispose(); xapStream = null; reader = null; if (!AppNodeFound) { error = XapReadError.NoAppElement; } else if (!ProductIdFound) { error = XapReadError.NoProductId; } if (error == XapReadError.NotRead) { error = XapReadError.Success; } if (deleteFile == true) { Functions.RemoveFile(TempFileName); } UpdateView(); return(true); }
public static string ConvertBase64(string encodeData) { System.Text.Encoding encode = System.Text.Encoding.UTF8; byte[] bytedata = encode.GetBytes(encodeData); return(Convert.ToBase64String(bytedata, 0, bytedata.Length)); }
static public bool readCSV(string filePath, out DataTable dt)//从csv读取数据返回table { dt = new DataTable(); try { System.Text.Encoding encoding = Encoding.Default;//GetType(filePath); // // DataTable dt = new DataTable(); System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding); //记录每次读取的一行记录 string strLine = ""; //记录每行记录中的各字段内容 string[] aryLine = null; string[] tableHead = null; //标示列数 int columnCount = 0; //标示是否是读取的第一行 bool IsFirst = true; //逐行读取CSV中的数据 while ((strLine = sr.ReadLine()) != null) { if (IsFirst == true) { tableHead = strLine.Split(','); IsFirst = false; columnCount = tableHead.Length; //创建列 for (int i = 0; i < columnCount; i++) { DataColumn dc = new DataColumn(tableHead[i]); dt.Columns.Add(dc); } } else { aryLine = strLine.Split(','); DataRow dr = dt.NewRow(); for (int j = 0; j < columnCount; j++) { dr[j] = aryLine[j]; } dt.Rows.Add(dr); } } if (aryLine != null && aryLine.Length > 0) { dt.DefaultView.Sort = tableHead[0] + " " + "asc"; } sr.Close(); fs.Close(); return(true); } catch (Exception e) { MessageBox.Show(filePath + " 解析失败!\n" + e.Message, "CSV读取出错", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
public void GetInformation(IMediaImage imagePlugin, Partition partition, out string information, Encoding encoding) { Encoding = new LisaRoman(); information = ""; StringBuilder sb = new StringBuilder(); try { if (imagePlugin.Info.ReadableSectorTags == null) { return; } if (!imagePlugin.Info.ReadableSectorTags.Contains(SectorTagType.AppleSectorTag)) { return; } // Minimal LisaOS disk is 3.5" single sided double density, 800 sectors if (imagePlugin.Info.Sectors < 800) { return; } int beforeMddf = -1; // LisaOS searches sectors until tag tells MDDF resides there, so we'll search 100 sectors for (int i = 0; i < 100; i++) { DecodeTag(imagePlugin.ReadSectorTag((ulong)i, SectorTagType.AppleSectorTag), out LisaTag.PriamTag searchTag); DicConsole.DebugWriteLine("LisaFS plugin", "Sector {0}, file ID 0x{1:X4}", i, searchTag.FileId); if (beforeMddf == -1 && searchTag.FileId == FILEID_LOADER_SIGNED) { beforeMddf = i - 1; } if (searchTag.FileId != FILEID_MDDF) { continue; } byte[] sector = imagePlugin.ReadSector((ulong)i); MDDF infoMddf = new MDDF(); byte[] pString = new byte[33]; infoMddf.fsversion = BigEndianBitConverter.ToUInt16(sector, 0x00); infoMddf.volid = BigEndianBitConverter.ToUInt64(sector, 0x02); infoMddf.volnum = BigEndianBitConverter.ToUInt16(sector, 0x0A); Array.Copy(sector, 0x0C, pString, 0, 33); infoMddf.volname = StringHandlers.PascalToString(pString, Encoding); infoMddf.unknown1 = sector[0x2D]; Array.Copy(sector, 0x2E, pString, 0, 33); // Prevent garbage infoMddf.password = pString[0] <= 32 ? StringHandlers.PascalToString(pString, Encoding) : ""; infoMddf.unknown2 = sector[0x4F]; infoMddf.machine_id = BigEndianBitConverter.ToUInt32(sector, 0x50); infoMddf.master_copy_id = BigEndianBitConverter.ToUInt32(sector, 0x54); uint lisaTime = BigEndianBitConverter.ToUInt32(sector, 0x58); infoMddf.dtvc = DateHandlers.LisaToDateTime(lisaTime); lisaTime = BigEndianBitConverter.ToUInt32(sector, 0x5C); infoMddf.dtcc = DateHandlers.LisaToDateTime(lisaTime); lisaTime = BigEndianBitConverter.ToUInt32(sector, 0x60); infoMddf.dtvb = DateHandlers.LisaToDateTime(lisaTime); lisaTime = BigEndianBitConverter.ToUInt32(sector, 0x64); infoMddf.dtvs = DateHandlers.LisaToDateTime(lisaTime); infoMddf.unknown3 = BigEndianBitConverter.ToUInt32(sector, 0x68); infoMddf.mddf_block = BigEndianBitConverter.ToUInt32(sector, 0x6C); infoMddf.volsize_minus_one = BigEndianBitConverter.ToUInt32(sector, 0x70); infoMddf.volsize_minus_mddf_minus_one = BigEndianBitConverter.ToUInt32(sector, 0x74); infoMddf.vol_size = BigEndianBitConverter.ToUInt32(sector, 0x78); infoMddf.blocksize = BigEndianBitConverter.ToUInt16(sector, 0x7C); infoMddf.datasize = BigEndianBitConverter.ToUInt16(sector, 0x7E); infoMddf.unknown4 = BigEndianBitConverter.ToUInt16(sector, 0x80); infoMddf.unknown5 = BigEndianBitConverter.ToUInt32(sector, 0x82); infoMddf.unknown6 = BigEndianBitConverter.ToUInt32(sector, 0x86); infoMddf.clustersize = BigEndianBitConverter.ToUInt16(sector, 0x8A); infoMddf.fs_size = BigEndianBitConverter.ToUInt32(sector, 0x8C); infoMddf.unknown7 = BigEndianBitConverter.ToUInt32(sector, 0x90); infoMddf.srec_ptr = BigEndianBitConverter.ToUInt32(sector, 0x94); infoMddf.unknown9 = BigEndianBitConverter.ToUInt16(sector, 0x98); infoMddf.srec_len = BigEndianBitConverter.ToUInt16(sector, 0x9A); infoMddf.unknown10 = BigEndianBitConverter.ToUInt32(sector, 0x9C); infoMddf.unknown11 = BigEndianBitConverter.ToUInt32(sector, 0xA0); infoMddf.unknown12 = BigEndianBitConverter.ToUInt32(sector, 0xA4); infoMddf.unknown13 = BigEndianBitConverter.ToUInt32(sector, 0xA8); infoMddf.unknown14 = BigEndianBitConverter.ToUInt32(sector, 0xAC); infoMddf.filecount = BigEndianBitConverter.ToUInt16(sector, 0xB0); infoMddf.unknown15 = BigEndianBitConverter.ToUInt32(sector, 0xB2); infoMddf.unknown16 = BigEndianBitConverter.ToUInt32(sector, 0xB6); infoMddf.freecount = BigEndianBitConverter.ToUInt32(sector, 0xBA); infoMddf.unknown17 = BigEndianBitConverter.ToUInt16(sector, 0xBE); infoMddf.unknown18 = BigEndianBitConverter.ToUInt32(sector, 0xC0); infoMddf.overmount_stamp = BigEndianBitConverter.ToUInt64(sector, 0xC4); infoMddf.serialization = BigEndianBitConverter.ToUInt32(sector, 0xCC); infoMddf.unknown19 = BigEndianBitConverter.ToUInt32(sector, 0xD0); infoMddf.unknown_timestamp = BigEndianBitConverter.ToUInt32(sector, 0xD4); infoMddf.unknown20 = BigEndianBitConverter.ToUInt32(sector, 0xD8); infoMddf.unknown21 = BigEndianBitConverter.ToUInt32(sector, 0xDC); infoMddf.unknown22 = BigEndianBitConverter.ToUInt32(sector, 0xE0); infoMddf.unknown23 = BigEndianBitConverter.ToUInt32(sector, 0xE4); infoMddf.unknown24 = BigEndianBitConverter.ToUInt32(sector, 0xE8); infoMddf.unknown25 = BigEndianBitConverter.ToUInt32(sector, 0xEC); infoMddf.unknown26 = BigEndianBitConverter.ToUInt32(sector, 0xF0); infoMddf.unknown27 = BigEndianBitConverter.ToUInt32(sector, 0xF4); infoMddf.unknown28 = BigEndianBitConverter.ToUInt32(sector, 0xF8); infoMddf.unknown29 = BigEndianBitConverter.ToUInt32(sector, 0xFC); infoMddf.unknown30 = BigEndianBitConverter.ToUInt32(sector, 0x100); infoMddf.unknown31 = BigEndianBitConverter.ToUInt32(sector, 0x104); infoMddf.unknown32 = BigEndianBitConverter.ToUInt32(sector, 0x108); infoMddf.unknown33 = BigEndianBitConverter.ToUInt32(sector, 0x10C); infoMddf.unknown34 = BigEndianBitConverter.ToUInt32(sector, 0x110); infoMddf.unknown35 = BigEndianBitConverter.ToUInt32(sector, 0x114); infoMddf.backup_volid = BigEndianBitConverter.ToUInt64(sector, 0x118); infoMddf.label_size = BigEndianBitConverter.ToUInt16(sector, 0x120); infoMddf.fs_overhead = BigEndianBitConverter.ToUInt16(sector, 0x122); infoMddf.result_scavenge = BigEndianBitConverter.ToUInt16(sector, 0x124); infoMddf.boot_code = BigEndianBitConverter.ToUInt16(sector, 0x126); infoMddf.boot_environ = BigEndianBitConverter.ToUInt16(sector, 0x6C); infoMddf.unknown36 = BigEndianBitConverter.ToUInt32(sector, 0x12A); infoMddf.unknown37 = BigEndianBitConverter.ToUInt32(sector, 0x12E); infoMddf.unknown38 = BigEndianBitConverter.ToUInt32(sector, 0x132); infoMddf.vol_sequence = BigEndianBitConverter.ToUInt16(sector, 0x136); infoMddf.vol_left_mounted = sector[0x138]; DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown1 = 0x{0:X2} ({0})", infoMddf.unknown1); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown2 = 0x{0:X2} ({0})", infoMddf.unknown2); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown3 = 0x{0:X8} ({0})", infoMddf.unknown3); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown4 = 0x{0:X4} ({0})", infoMddf.unknown4); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown5 = 0x{0:X8} ({0})", infoMddf.unknown5); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown6 = 0x{0:X8} ({0})", infoMddf.unknown6); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown7 = 0x{0:X8} ({0})", infoMddf.unknown7); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown9 = 0x{0:X4} ({0})", infoMddf.unknown9); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown10 = 0x{0:X8} ({0})", infoMddf.unknown10); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown11 = 0x{0:X8} ({0})", infoMddf.unknown11); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown12 = 0x{0:X8} ({0})", infoMddf.unknown12); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown13 = 0x{0:X8} ({0})", infoMddf.unknown13); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown14 = 0x{0:X8} ({0})", infoMddf.unknown14); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown15 = 0x{0:X8} ({0})", infoMddf.unknown15); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown16 = 0x{0:X8} ({0})", infoMddf.unknown16); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown17 = 0x{0:X4} ({0})", infoMddf.unknown17); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown18 = 0x{0:X8} ({0})", infoMddf.unknown18); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown19 = 0x{0:X8} ({0})", infoMddf.unknown19); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown20 = 0x{0:X8} ({0})", infoMddf.unknown20); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown21 = 0x{0:X8} ({0})", infoMddf.unknown21); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown22 = 0x{0:X8} ({0})", infoMddf.unknown22); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown23 = 0x{0:X8} ({0})", infoMddf.unknown23); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown24 = 0x{0:X8} ({0})", infoMddf.unknown24); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown25 = 0x{0:X8} ({0})", infoMddf.unknown25); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown26 = 0x{0:X8} ({0})", infoMddf.unknown26); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown27 = 0x{0:X8} ({0})", infoMddf.unknown27); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown28 = 0x{0:X8} ({0})", infoMddf.unknown28); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown29 = 0x{0:X8} ({0})", infoMddf.unknown29); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown30 = 0x{0:X8} ({0})", infoMddf.unknown30); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown31 = 0x{0:X8} ({0})", infoMddf.unknown31); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown32 = 0x{0:X8} ({0})", infoMddf.unknown32); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown33 = 0x{0:X8} ({0})", infoMddf.unknown33); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown34 = 0x{0:X8} ({0})", infoMddf.unknown34); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown35 = 0x{0:X8} ({0})", infoMddf.unknown35); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown36 = 0x{0:X8} ({0})", infoMddf.unknown36); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown37 = 0x{0:X8} ({0})", infoMddf.unknown37); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown38 = 0x{0:X8} ({0})", infoMddf.unknown38); DicConsole.DebugWriteLine("LisaFS plugin", "mddf.unknown_timestamp = 0x{0:X8} ({0}, {1})", infoMddf.unknown_timestamp, DateHandlers.LisaToDateTime(infoMddf.unknown_timestamp)); if (infoMddf.mddf_block != i - beforeMddf) { return; } if (infoMddf.vol_size > imagePlugin.Info.Sectors) { return; } if (infoMddf.vol_size - 1 != infoMddf.volsize_minus_one) { return; } if (infoMddf.vol_size - i - 1 != infoMddf.volsize_minus_mddf_minus_one - beforeMddf) { return; } if (infoMddf.datasize > infoMddf.blocksize) { return; } if (infoMddf.blocksize < imagePlugin.Info.SectorSize) { return; } if (infoMddf.datasize != imagePlugin.Info.SectorSize) { return; } switch (infoMddf.fsversion) { case LISA_V1: sb.AppendLine("LisaFS v1"); break; case LISA_V2: sb.AppendLine("LisaFS v2"); break; case LISA_V3: sb.AppendLine("LisaFS v3"); break; default: sb.AppendFormat("Uknown LisaFS version {0}", infoMddf.fsversion).AppendLine(); break; } sb.AppendFormat("Volume name: \"{0}\"", infoMddf.volname).AppendLine(); sb.AppendFormat("Volume password: \"{0}\"", infoMddf.password).AppendLine(); sb.AppendFormat("Volume ID: 0x{0:X16}", infoMddf.volid).AppendLine(); sb.AppendFormat("Backup volume ID: 0x{0:X16}", infoMddf.backup_volid).AppendLine(); sb.AppendFormat("Master copy ID: 0x{0:X8}", infoMddf.master_copy_id).AppendLine(); sb.AppendFormat("Volume is number {0} of {1}", infoMddf.volnum, infoMddf.vol_sequence).AppendLine(); sb.AppendFormat("Serial number of Lisa computer that created this volume: {0}", infoMddf.machine_id) .AppendLine(); sb.AppendFormat("Serial number of Lisa computer that can use this volume's software {0}", infoMddf.serialization).AppendLine(); sb.AppendFormat("Volume created on {0}", infoMddf.dtvc).AppendLine(); sb.AppendFormat("Some timestamp, says {0}", infoMddf.dtcc).AppendLine(); sb.AppendFormat("Volume backed up on {0}", infoMddf.dtvb).AppendLine(); sb.AppendFormat("Volume scavenged on {0}", infoMddf.dtvs).AppendLine(); sb.AppendFormat("MDDF is in block {0}", infoMddf.mddf_block + beforeMddf).AppendLine(); sb.AppendFormat("There are {0} reserved blocks before volume", beforeMddf).AppendLine(); sb.AppendFormat("{0} blocks minus one", infoMddf.volsize_minus_one).AppendLine(); sb.AppendFormat("{0} blocks minus one minus MDDF offset", infoMddf.volsize_minus_mddf_minus_one) .AppendLine(); sb.AppendFormat("{0} blocks in volume", infoMddf.vol_size).AppendLine(); sb.AppendFormat("{0} bytes per sector (uncooked)", infoMddf.blocksize).AppendLine(); sb.AppendFormat("{0} bytes per sector", infoMddf.datasize).AppendLine(); sb.AppendFormat("{0} blocks per cluster", infoMddf.clustersize).AppendLine(); sb.AppendFormat("{0} blocks in filesystem", infoMddf.fs_size).AppendLine(); sb.AppendFormat("{0} files in volume", infoMddf.filecount).AppendLine(); sb.AppendFormat("{0} blocks free", infoMddf.freecount).AppendLine(); sb.AppendFormat("{0} bytes in LisaInfo", infoMddf.label_size).AppendLine(); sb.AppendFormat("Filesystem overhead: {0}", infoMddf.fs_overhead).AppendLine(); sb.AppendFormat("Scanvenger result code: 0x{0:X8}", infoMddf.result_scavenge).AppendLine(); sb.AppendFormat("Boot code: 0x{0:X8}", infoMddf.boot_code).AppendLine(); sb.AppendFormat("Boot environment: 0x{0:X8}", infoMddf.boot_environ).AppendLine(); sb.AppendFormat("Overmount stamp: 0x{0:X16}", infoMddf.overmount_stamp).AppendLine(); sb.AppendFormat("S-Records start at {0} and spans for {1} blocks", infoMddf.srec_ptr + infoMddf.mddf_block + beforeMddf, infoMddf.srec_len) .AppendLine(); sb.AppendLine(infoMddf.vol_left_mounted == 0 ? "Volume is clean" : "Volume is dirty"); information = sb.ToString(); XmlFsType = new FileSystemType(); if (DateTime.Compare(infoMddf.dtvb, DateHandlers.LisaToDateTime(0)) > 0) { XmlFsType.BackupDate = infoMddf.dtvb; XmlFsType.BackupDateSpecified = true; } XmlFsType.Clusters = infoMddf.vol_size; XmlFsType.ClusterSize = (uint)(infoMddf.clustersize * infoMddf.datasize); if (DateTime.Compare(infoMddf.dtvc, DateHandlers.LisaToDateTime(0)) > 0) { XmlFsType.CreationDate = infoMddf.dtvc; XmlFsType.CreationDateSpecified = true; } XmlFsType.Dirty = infoMddf.vol_left_mounted != 0; XmlFsType.Files = infoMddf.filecount; XmlFsType.FilesSpecified = true; XmlFsType.FreeClusters = infoMddf.freecount; XmlFsType.FreeClustersSpecified = true; XmlFsType.Type = "LisaFS"; XmlFsType.VolumeName = infoMddf.volname; XmlFsType.VolumeSerial = $"{infoMddf.volid:X16}"; return; } } catch (Exception ex) { DicConsole.ErrorWriteLine("Exception {0}, {1}, {2}", ex.Message, ex.InnerException, ex.StackTrace); } }
/// <summary>Set the encoding for the commit information</summary> /// <param name="enc">the encoding to use.</param> public virtual void SetEncoding(System.Text.Encoding enc) { encoding = enc; }
public static byte[] GetByteArrayFromString(string str) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; return(encoding.GetBytes(str)); }
/// <summary>Set the encoding for the commit information</summary> /// <param name="encodingName"> /// the encoding name. See /// <see cref="Sharpen.Extensions.GetEncoding(string)">Sharpen.Extensions.GetEncoding(string) /// </see> /// . /// </param> public virtual void SetEncoding(string encodingName) { encoding = Sharpen.Extensions.GetEncoding(encodingName); }
public StringWriterWithEncoding(StringBuilder sb, System.Text.Encoding encoding) : base(sb) { this._encoding = encoding; }
//등록 자료 생성 //2013.01.18 태희철 수정 public static string ConvertRegister(string path, string xmlZipcodeAreaPath, string xmlZipcodePath) { System.Text.Encoding _encoding = System.Text.Encoding.GetEncoding(strEncoding); //기본 인코딩 StreamReader _sr = null; //파일 읽기 스트림 StreamWriter _swError = null; StreamWriter _sw = null; string _strDataCode = ""; // 사용데이터 구분 string _strCodeType = ""; // 공카드구분 string _strCustomer_ssn = ""; // 기프트구분 string _strOwner_only = ""; // 기프트구분 string _strLine = ""; string _strReturn = ""; string[] _strAry = null; DataTable _dtable = null; DataSet _dsetZipcodeArea = null; try { _dtable = new DataTable("CONVERT"); _dsetZipcodeArea = new DataSet(); _dsetZipcodeArea.ReadXml(xmlZipcodeAreaPath); //파일 읽기 Stream과 오류시 저장할 쓰기 Stream 생성 _sr = new StreamReader(path, _encoding); _swError = new StreamWriter(path + ".Error", false, _encoding); while ((_strLine = _sr.ReadLine()) != null) { //CSV 분리 _strAry = _strLine.Split(chCSV); //발송구분코드 : 36,46 = 블랙, 37 = 스마트일반, 45 = 동의서, 47 = 스마트동의 _strCodeType = _strAry[5].Trim(); //구분코드 _strCustomer_ssn = _strAry[10].Trim(); //일반 중 본인만 수령 가능 코드 : 00 = 본인만, 01 = 3자수령가능 _strOwner_only = _strAry[74].Trim(); //2014.09.02 태희철 기프트카드 구분 if (_strCustomer_ssn.Trim() == "") { _sw = new StreamWriter(path + "일반_기프트", true, _encoding); _sw.WriteLine(_strLine + ";0581102"); } //2013.01.14 태희철 수정 01:클럽, 02:대한, 03:아시아, 04:하이플러스 else if (_strCodeType == "36") { _sw = new StreamWriter(path + "블랙카드", true, _encoding); _sw.WriteLine(_strLine + ";0583102"); } else if (_strCodeType == "46") { _sw = new StreamWriter(path + "블랙_동의", true, _encoding); _sw.WriteLine(_strLine + ";0582107"); } else if (_strCodeType == "56") { _sw = new StreamWriter(path + "블랙_약식", true, _encoding); _sw.WriteLine(_strLine + ";0582108"); } else if (_strCodeType == "55") { _sw = new StreamWriter(path + "현대약식동의", true, _encoding); _sw.WriteLine(_strLine + ";0582103"); } else if (_strCodeType == "37") { if (_strOwner_only.Trim() == "00" || _strOwner_only.Trim() == "10" || _strOwner_only.Trim() == "20") { _sw = new StreamWriter(path + "스마트일반_본인", true, _encoding); _sw.WriteLine(_strLine + ";0583103"); } else { _sw = new StreamWriter(path + "스마트일반", true, _encoding); _sw.WriteLine(_strLine + ";0583101"); } } else if (_strCodeType == "47") { _sw = new StreamWriter(path + "스마트동의", true, _encoding); _sw.WriteLine(_strLine + ";0582102"); } else if (_strCodeType == "45") { _sw = new StreamWriter(path + "현대동의", true, _encoding); _sw.WriteLine(_strLine + ";0582101"); } else if (_strCodeType == "57") { _sw = new StreamWriter(path + "현대스마트약식동의", true, _encoding); _sw.WriteLine(_strLine + ";0582104"); } else if (_strCodeType == "30" && (_strOwner_only.Trim() == "00" || _strOwner_only.Trim() == "10" || _strOwner_only.Trim() == "20")) { _sw = new StreamWriter(path + "일반_본인만", true, _encoding); _sw.WriteLine(_strLine + ";0581103"); } else if (_strCodeType == "30") { _sw = new StreamWriter(path + "일반", true, _encoding); _sw.WriteLine(_strLine + ";0581101"); } else { _sw = new StreamWriter(path + "_그외_오류", true, _encoding); _sw.WriteLine(_strLine); } _sw.Close(); } _sr.Close(); _strReturn = "성공"; } catch (Exception ex) { _strReturn = "실패"; if (_swError != null) { _swError.WriteLine(ex.Message); } } finally { if (_sr != null) { _sr.Close(); } if (_sw != null) { _sw.Close(); } if (_swError != null) { _swError.Close(); } } return(_strReturn); }
internal CommandStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base(connectionPool, lifetime, checkLifetime) { this.m_Buffer = string.Empty; this.m_Encoding = System.Text.Encoding.UTF8; this.m_Decoder = this.m_Encoding.GetDecoder(); }
public void GetInformation(IMediaImage imagePlugin, Partition partition, out string information, Encoding encoding) { Encoding = encoding ?? new Apple2(); var sbInformation = new StringBuilder(); information = ""; multiplier = (uint)(imagePlugin.Info.SectorSize == 256 ? 2 : 1); if (imagePlugin.Info.Sectors < 3) { return; } // Blocks 0 and 1 are boot code byte[] volBlock = imagePlugin.ReadSectors((multiplier * 2) + partition.Start, multiplier); // On Apple //, it's little endian // TODO: Fix //BigEndianBitConverter.IsLittleEndian = // multiplier == 2 ? !BitConverter.IsLittleEndian : BitConverter.IsLittleEndian; var volEntry = new PascalVolumeEntry { FirstBlock = BigEndianBitConverter.ToInt16(volBlock, 0x00), LastBlock = BigEndianBitConverter.ToInt16(volBlock, 0x02), EntryType = (PascalFileKind)BigEndianBitConverter.ToInt16(volBlock, 0x04), VolumeName = new byte[8], Blocks = BigEndianBitConverter.ToInt16(volBlock, 0x0E), Files = BigEndianBitConverter.ToInt16(volBlock, 0x10), Dummy = BigEndianBitConverter.ToInt16(volBlock, 0x12), LastBoot = BigEndianBitConverter.ToInt16(volBlock, 0x14), Tail = BigEndianBitConverter.ToInt32(volBlock, 0x16) }; Array.Copy(volBlock, 0x06, volEntry.VolumeName, 0, 8); // First block is always 0 (even is it's sector 2) if (volEntry.FirstBlock != 0) { return; } // Last volume record block must be after first block, and before end of device if (volEntry.LastBlock <= volEntry.FirstBlock || (ulong)volEntry.LastBlock > (imagePlugin.Info.Sectors / multiplier) - 2) { return; } // Volume record entry type must be volume or secure if (volEntry.EntryType != PascalFileKind.Volume && volEntry.EntryType != PascalFileKind.Secure) { return; } // Volume name is max 7 characters if (volEntry.VolumeName[0] > 7) { return; } // Volume blocks is equal to volume sectors if (volEntry.Blocks < 0 || (ulong)volEntry.Blocks != imagePlugin.Info.Sectors / multiplier) { return; } // There can be not less than zero files if (volEntry.Files < 0) { return; } sbInformation.AppendFormat("Volume record spans from block {0} to block {1}", volEntry.FirstBlock, volEntry.LastBlock).AppendLine(); sbInformation. AppendFormat("Volume name: {0}", StringHandlers.PascalToString(volEntry.VolumeName, Encoding)). AppendLine(); sbInformation.AppendFormat("Volume has {0} blocks", volEntry.Blocks).AppendLine(); sbInformation.AppendFormat("Volume has {0} files", volEntry.Files).AppendLine(); sbInformation. AppendFormat("Volume last booted at {0}", DateHandlers.UcsdPascalToDateTime(volEntry.LastBoot)). AppendLine(); information = sbInformation.ToString(); XmlFsType = new FileSystemType { Bootable = !ArrayHelpers.ArrayIsNullOrEmpty(imagePlugin.ReadSectors(partition.Start, multiplier * 2)), Clusters = (ulong)volEntry.Blocks, ClusterSize = imagePlugin.Info.SectorSize, Files = (ulong)volEntry.Files, FilesSpecified = true, Type = "UCSD Pascal", VolumeName = StringHandlers.PascalToString(volEntry.VolumeName, Encoding) }; }
private void button1_Click(object sender, EventArgs e) { // サーバーのIPアドレス(または、ホスト名)とポート番号 string ipOrHost = "127.0.0.1"; // long ipOrHost = "127.0.0.1"; int port = 1024; byte[] byteIpAddress = { 192, 168, 1, 6 }; byte[] localIpAddress = { 192, 168, 1, 6 }; try { // System.Net.IPAddress ipAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0]; System.Net.IPAddress ipAddress = new System.Net.IPAddress(byteIpAddress); System.Net.IPAddress ipAddress2 = new System.Net.IPAddress(localIpAddress); System.Net.IPEndPoint ipLocalEndPoint = new System.Net.IPEndPoint(ipAddress2, 60000); System.Net.IPEndPoint ipRemotePoint = new System.Net.IPEndPoint(ipAddress, 1024); System.Net.Sockets.TcpClient tcpClientA = new System.Net.Sockets.TcpClient(ipLocalEndPoint); tcpClientA.Connect(ipRemotePoint); // tcpClientA.Connect(ipLocalEndPoint); // System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); // System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); // NetworkStreamを取得する // System.Net.Sockets.NetworkStream ns = tcp.GetStream(); System.Net.Sockets.NetworkStream ns = tcpClientA.GetStream(); // ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; string sendMsg = this.textBox1.Text; // サーバーにデータを送信する // 文字列をbyte型配列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; // byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); // byte[] sendBytes = { 0x01, 0x02, 0x03, 0x04 }; byte[] sendBytes = new byte[sendMsg.Length]; for (int i = 0; i < sendMsg.Length; i++) { sendBytes[i] = (byte)sendMsg[i]; } sendBytes[0] = 0x00; sendBytes[1] = 0x01; byte[] buf = Encoding.ASCII.GetBytes(sendMsg); byte[] buf2 = FromHexString(sendMsg);; // buf2[0] = BitConverter.ToSingle(buf[0], 0); // データを送信する // ns.Write(sendBytes, 0, sendBytes.Length); ns.Write(buf2, 0, buf2.Length); // コミットテスト // 閉じる ns.Close(); // tcp.Close(); tcpClientA.Close(); } catch (Exception) { textBox1.Text = "エラーが発生しました"; } finally { } }
private Encoding(System.Text.Encoding value, bool supportsByteOrderMark) { this.value = value; this.supportsByteOrderMark = supportsByteOrderMark; }
private void btnOK_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtURL.Text)) { txtResponse.Text = ""; try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtURL.Text); req.Method = metodoRequest.Text; req.PreAuthenticate = true; req.ProtocolVersion = System.Net.HttpVersion.Version10; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(txtLogin.Text + ":" + txtSenha.Text)); req.Credentials = new NetworkCredential("username", "password"); var type = req.GetType(); var currentMethod = type.GetProperty("CurrentMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(req); var methodType = currentMethod.GetType(); methodType.GetField("ContentBodyNotAllowed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(currentMethod, false); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; if (!string.IsNullOrEmpty(txtJson.Text)) { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txtJson.Text); req.ContentType = "application/json; charset=utf-8"; req.ContentLength = byteArray.Length; var dataStream = req.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); } else { //throw new Exception("Erro: JSON não informado."); } System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse; System.IO.Stream receiveStream = resp.GetResponseStream(); System.Text.Encoding encode = Encoding.GetEncoding("utf-8"); // Pipes the stream to a higher level stream reader with the required encoding format. System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, encode); Char[] read = new Char[256]; // Reads 256 characters at a time. int count = readStream.Read(read, 0, 256); while (count > 0) { // Dumps the 256 characters on a string and displays the string to the console. String str = new String(read, 0, count); txtResponse.Text += (str); count = readStream.Read(read, 0, 256); } System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(txtResponse.Text); System.Xml.XmlReader xmlReader = new System.Xml.XmlNodeReader(xDoc); DataSet dsXml = new DataSet(); dsXml.ReadXml(xmlReader); foreach (DataTable dt in dsXml.Tables) { if (dt.TableName == "value") { gridXMLDataTable.DataSource = dt; } } // Releases the resources of the response. resp.Close(); // Releases the resources of the Stream. readStream.Close(); } catch (Exception ex) { txtResponse.Text = "Erro ao consumir a API " + txtURL.Text + ". Exceção: " + ex.Message + ". Trace: " + ex.InnerException; } } }
//The engine calls this method to change the encoding of the //generated text output file based on the optional output directive //if the user specifies it in the text template. //---------------------------------------------------------------------- public virtual void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective) { FileEncoding = encoding; }
internal NSString(byte[] bytes, System.Text.Encoding encoding) { content = StringUtils.GetString(bytes, encoding); }
/// <summary> /// Initializes this instance of EndianAwareBinaryReader with the given input stream /// and text encoding, and assuming native Endianness /// </summary> /// <param name="output">The stream to read input From</param> /// <param name="encoding">The encoding to read text with</param> public EndianAwareBinaryReader(System.IO.Stream output, System.Text.Encoding encoding) : this(output, encoding, System.DataConverter.Native) { } // Nothing to do
/// <summary>Initialize an empty commit.</summary> /// <remarks>Initialize an empty commit.</remarks> public CommitBuilder() { parentIds = EMPTY_OBJECTID_LIST; encoding = Constants.CHARSET; }
public Encoding GetEncoding(string name) { return(new Encoding(NetEncoding.GetEncoding(name))); }
public File(string path, string changesFolder, System.Text.Encoding encoding) : base(path, changesFolder, encoding) { GameOps = new Op[128]; GameOps[0x00] = new Op { Code = 0x00, Name = "Nop", ParamCount = 0 }; GameOps[0x01] = new Op { Code = 0x01, Name = "NewLine", ParamCount = 0 }; GameOps[0x02] = new Op { Code = 0x02, Name = "ReadKey", ParamCount = 0 }; GameOps[0x03] = new Op { Code = 0x03, Name = "SetTextColor", ParamCount = 1 }; GameOps[0x04] = new Op { Code = 0x04, Name = "Op_04", ParamCount = 1 }; // Parece algo de una tecla pulsada (GSJoy.Trg) GameOps[0x05] = new Op { Code = 0x05, Name = "PlayBGM", ParamCount = 2 }; GameOps[0x06] = new Op { Code = 0x06, Name = "ControlSE", ParamCount = 2 }; GameOps[0x07] = new Op { Code = 0x07, Name = "Op_07", ParamCount = 0 }; // Comparte código con 0x02 (ReadKey) pero no se exactamente qué hace GameOps[0x08] = new Op { Code = 0x08, Name = "Op_08", ParamCount = 2 }; GameOps[0x09] = new Op { Code = 0x09, Name = "Op_09", ParamCount = 3 }; GameOps[0x0A] = new Op { Code = 0x0A, Name = "Op_0A", ParamCount = 1 }; // Comparte código con 0x02 (ReadKey) pero no se exactamente qué hace GameOps[0x0B] = new Op { Code = 0x0B, Name = "SetMessageTime", ParamCount = 1 }; GameOps[0x0C] = new Op { Code = 0x0C, Name = "Wait", ParamCount = 1 }; GameOps[0x0D] = new Op { Code = 0x0D, Name = "Exit", ParamCount = 0 }; GameOps[0x0E] = new Op { Code = 0x0E, Name = "SetSpeakerId", ParamCount = 1 }; GameOps[0x0F] = new Op { Code = 0x0F, Name = "SetTukkomi", ParamCount = 1 }; GameOps[0x10] = new Op { Code = 0x10, Name = "SetGSFlag", ParamCount = 1 }; GameOps[0x11] = new Op { Code = 0x11, Name = "Op_11", ParamCount = 0 }; GameOps[0x12] = new Op { Code = 0x12, Name = "PlayFadeCtrl", ParamCount = 3 }; GameOps[0x13] = new Op { Code = 0x13, Name = "SetItemPlateCtrl", ParamCount = 1 }; GameOps[0x14] = new Op { Code = 0x14, Name = "CloseItemPlateCtrl", ParamCount = 0 }; GameOps[0x15] = new Op { Code = 0x15, Name = "Op_15", ParamCount = 0 }; GameOps[0x16] = new Op { Code = 0x16, Name = "NextScenario", ParamCount = 0 }; GameOps[0x17] = new Op { Code = 0x17, Name = "AddRecord", ParamCount = 1 }; GameOps[0x18] = new Op { Code = 0x18, Name = "DeleteRecord", ParamCount = 1 }; GameOps[0x19] = new Op { Code = 0x19, Name = "UpdateRecord", ParamCount = 2 }; GameOps[0x1A] = new Op { Code = 0x1A, Name = "CourtScroll", ParamCount = 4 }; GameOps[0x1B] = new Op { Code = 0x1B, Name = "SetBackground", ParamCount = 1 }; GameOps[0x1C] = new Op { Code = 0x1C, Name = "Op_1C", ParamCount = 1 }; GameOps[0x1D] = new Op { Code = 0x1D, Name = "ScrollBackground", ParamCount = 1 }; GameOps[0x1E] = new Op { Code = 0x1E, Name = "PlayCharacterAnimation", ParamCount = 3 }; GameOps[0x1F] = new Op { Code = 0x1F, Name = "StopCutUpScroll", ParamCount = 0 }; GameOps[0x20] = new Op { Code = 0x20, Name = "SetNextNumber", ParamCount = 1 }; GameOps[0x21] = new Op { Code = 0x21, Name = "Op_21", ParamCount = 0 }; GameOps[0x22] = new Op { Code = 0x22, Name = "FadeOutBGM", ParamCount = 2 }; GameOps[0x23] = new Op { Code = 0x23, Name = "ReplayBGM", ParamCount = 2 }; GameOps[0x24] = new Op { Code = 0x24, Name = "Op_24", ParamCount = 0 }; GameOps[0x25] = new Op { Code = 0x25, Name = "Nop2", ParamCount = 0 }; GameOps[0x26] = new Op { Code = 0x26, Name = "SetStatusFlag", ParamCount = 1 }; GameOps[0x27] = new Op { Code = 0x27, Name = "Quake", ParamCount = 2 }; GameOps[0x28] = new Op { Code = 0x28, Name = "Op_28", ParamCount = 1 }; GameOps[0x29] = new Op { Code = 0x29, Name = "Op_29", ParamCount = 1 }; GameOps[0x2A] = new Op { Code = 0x2A, Name = "Op_2A", ParamCount = 3 }; GameOps[0x2B] = new Op { Code = 0x2B, Name = "DoDamage", ParamCount = 0 }; GameOps[0x2C] = new Op { Code = 0x2C, Name = "Op_2C", ParamCount = 1 }; GameOps[0x2D] = new Op { Code = 0x2D, Name = "Op_2D", ParamCount = 0 }; // Comparte código con 0x02 (ReadKey) pero no se exactamente qué hace GameOps[0x2E] = new Op { Code = 0x2E, Name = "ClearText", ParamCount = 0 }; GameOps[0x2F] = new Op { Code = 0x2F, Name = "PlayObjectAnimation", ParamCount = 2 }; GameOps[0x30] = new Op { Code = 0x30, Name = "SetMessageSE", ParamCount = 1 }; GameOps[0x31] = new Op { Code = 0x31, Name = "CharFade", ParamCount = 2 }; GameOps[0x32] = new Op { Code = 0x32, Name = "MapData", ParamCount = 2 }; GameOps[0x33] = new Op { Code = 0x33, Name = "MapData2", ParamCount = 5 }; GameOps[0x34] = new Op { Code = 0x34, Name = "Op_34", ParamCount = 0 }; GameOps[0x35] = new Op { Code = 0x35, Name = "Op_35", ParamCount = 2 }; GameOps[0x36] = new Op { Code = 0x36, Name = "Op_36", ParamCount = 1 }; GameOps[0x37] = new Op { Code = 0x37, Name = "SetTalkDataSw", ParamCount = 2 }; GameOps[0x38] = new Op { Code = 0x38, Name = "SetActiveCharacterAnimation", ParamCount = 1 }; GameOps[0x39] = new Op { Code = 0x39, Name = "LoadSprite", ParamCount = 1 }; GameOps[0x3A] = new Op { Code = 0x3A, Name = "SetMapIconPosition", ParamCount = 3 }; GameOps[0x3B] = new Op { Code = 0x3B, Name = "SetMapIconParameters", ParamCount = 2 }; GameOps[0x3C] = new Op { Code = 0x3C, Name = "MapIconBlink", ParamCount = 1 }; GameOps[0x3D] = new Op { Code = 0x3D, Name = "MapIconVisible", ParamCount = 1 }; GameOps[0x3E] = new Op { Code = 0x3E, Name = "Op_3E", ParamCount = 1 }; GameOps[0x3F] = new Op { Code = 0x3F, Name = "Op_3F", ParamCount = 0 }; GameOps[0x40] = new Op { Code = 0x40, Name = "SetStatusPointCursolOff", ParamCount = 0 }; GameOps[0x41] = new Op { Code = 0x41, Name = "SetSubWindowReqTMain", ParamCount = 0 }; GameOps[0x42] = new Op { Code = 0x42, Name = "SetSoundFlag", ParamCount = 1 }; GameOps[0x43] = new Op { Code = 0x43, Name = "SetLifeGauge", ParamCount = 1 }; GameOps[0x44] = new Op { Code = 0x44, Name = "Judgment", ParamCount = 1 }; GameOps[0x45] = new Op { Code = 0x45, Name = "Op_45", ParamCount = 0 }; GameOps[0x46] = new Op { Code = 0x46, Name = "CutIn", ParamCount = 1 }; GameOps[0x47] = new Op { Code = 0x47, Name = "VolumeChangeBGM", ParamCount = 2 }; GameOps[0x48] = new Op { Code = 0x48, Name = "SetMessageBoardPos", ParamCount = 2 }; GameOps[0x49] = new Op { Code = 0x49, Name = "Op_49", ParamCount = 0 }; GameOps[0x4A] = new Op { Code = 0x4A, Name = "CheckGuilty", ParamCount = 1 }; GameOps[0x4B] = new Op { Code = 0x4B, Name = "MapIconChangeUV", ParamCount = 2 }; GameOps[0x4C] = new Op { Code = 0x4C, Name = "IsBackgroundScrolling", ParamCount = 0 }; GameOps[0x4D] = new Op { Code = 0x4D, Name = "Op_4D", ParamCount = 0 }; GameOps[0x4E] = new Op { Code = 0x4E, Name = "AnimationGoIdle", ParamCount = 2 }; GameOps[0x4F] = new Op { Code = 0x4F, Name = "SetPsylockData", ParamCount = 7 }; GameOps[0x50] = new Op { Code = 0x50, Name = "ClearPsylock", ParamCount = 1 }; GameOps[0x51] = new Op { Code = 0x51, Name = "RoomSeqChange", ParamCount = 2 }; GameOps[0x52] = new Op { Code = 0x52, Name = "SetSubWindowReqMagatamaMenuOn", ParamCount = 1 }; GameOps[0x53] = new Op { Code = 0x53, Name = "DisablePsyMenu", ParamCount = 0 }; GameOps[0x54] = new Op { Code = 0x54, Name = "SetLifeGauge2", ParamCount = 2 }; GameOps[0x55] = new Op { Code = 0x55, Name = "Op_55", ParamCount = 1 }; GameOps[0x56] = new Op { Code = 0x56, Name = "Op_56", ParamCount = 0 }; GameOps[0x57] = new Op { Code = 0x57, Name = "Op_57", ParamCount = 1 }; GameOps[0x58] = new Op { Code = 0x58, Name = "PsylockDispResetStatic", ParamCount = 0 }; GameOps[0x59] = new Op { Code = 0x59, Name = "Op_59", ParamCount = 1 }; GameOps[0x5A] = new Op { Code = 0x5A, Name = "Op_5A", ParamCount = 1 }; GameOps[0x5B] = new Op { Code = 0x5B, Name = "TanteiMenuRecov", ParamCount = 2 }; GameOps[0x5C] = new Op { Code = 0x5C, Name = "MosaicRun", ParamCount = 3 }; GameOps[0x5D] = new Op { Code = 0x5D, Name = "SetTextFlag", ParamCount = 1 }; GameOps[0x5E] = new Op { Code = 0x5E, Name = "Op_5E", ParamCount = 0 }; GameOps[0x5F] = new Op { Code = 0x5F, Name = "MonochromeSet", ParamCount = 3 }; GameOps[0x60] = new Op { Code = 0x60, Name = "Op_60", ParamCount = 4 }; GameOps[0x61] = new Op { Code = 0x61, Name = "Op_61", ParamCount = 3 }; GameOps[0x62] = new Op { Code = 0x62, Name = "PsylockToNormalBackground", ParamCount = 0 }; GameOps[0x63] = new Op { Code = 0x63, Name = "PsylockRedisp", ParamCount = 0 }; GameOps[0x64] = new Op { Code = 0x64, Name = "Op_64", ParamCount = 1 }; GameOps[0x65] = new Op { Code = 0x65, Name = "SetBackgroundParts", ParamCount = 2 }; GameOps[0x66] = new Op { Code = 0x66, Name = "Op_66", ParamCount = 3 }; GameOps[0x67] = new Op { Code = 0x67, Name = "MessageInit", ParamCount = 0 }; GameOps[0x68] = new Op { Code = 0x68, Name = "Op_68", ParamCount = 0 }; GameOps[0x69] = new Op { Code = 0x69, Name = "Op_69", ParamCount = 2 }; GameOps[0x6A] = new Op { Code = 0x6A, Name = "LoadScenario", ParamCount = 1 }; GameOps[0x6B] = new Op { Code = 0x6B, Name = "Op_6B", ParamCount = 3 }; GameOps[0x6C] = new Op { Code = 0x6C, Name = "Op_6C", ParamCount = 0 }; // En el GS3 creo que tiene 1 parametro GameOps[0x6D] = new Op { Code = 0x6D, Name = "Op_6D", ParamCount = 1 }; GameOps[0x6E] = new Op { Code = 0x6E, Name = "SetStatusThreeLine", ParamCount = 1 }; GameOps[0x6F] = new Op { Code = 0x6F, Name = "SetBkEndMess", ParamCount = 1 }; GameOps[0x70] = new Op { Code = 0x70, Name = "Op_70", ParamCount = 0 }; GameOps[0x71] = new Op { Code = 0x71, Name = "Op_71", ParamCount = 3 }; GameOps[0x72] = new Op { Code = 0x72, Name = "Op_72", ParamCount = 0 }; GameOps[0x73] = new Op { Code = 0x73, Name = "Op_73", ParamCount = 0 }; GameOps[0x74] = new Op { Code = 0x74, Name = "Op_74", ParamCount = 2 }; GameOps[0x75] = new Op { Code = 0x75, Name = "SetVideo", ParamCount = 4 }; GameOps[0x76] = new Op { Code = 0x76, Name = "Op_76", ParamCount = 2 }; GameOps[0x77] = new Op { Code = 0x77, Name = "FadeOutSE", ParamCount = 2 }; GameOps[0x78] = new Op { Code = 0x78, Name = "Op_78", ParamCount = 1 }; GameOps[0x79] = new Op { Code = 0x79, Name = "Op_79", ParamCount = 0 }; GameOps[0x7A] = new Op { Code = 0x7A, Name = "Op_7A", ParamCount = 1 }; GameOps[0x7B] = new Op { Code = 0x7B, Name = "Op_7B", ParamCount = 2 }; GameOps[0x7C] = new Op { Code = 0x7C, Name = "GS2UpdateSc3Opening", ParamCount = 0 }; GameOps[0x7D] = new Op { Code = 0x7D, Name = "GS2HanabiraMove", ParamCount = 1 }; GameOps[0x7E] = new Op { Code = 0x7E, Name = "GS2SpotlightMoveFocus", ParamCount = 1 }; GameOps[0x7F] = new Op { Code = 0x7F, Name = "DrawIconText", ParamCount = 1 }; }