当前位置: 首页>>代码示例>>C#>>正文


C# StringReader.ReadToFirstChar方法代码示例

本文整理汇总了C#中System.IO.StringReader.ReadToFirstChar方法的典型用法代码示例。如果您正苦于以下问题:C# StringReader.ReadToFirstChar方法的具体用法?C# StringReader.ReadToFirstChar怎么用?C# StringReader.ReadToFirstChar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.StringReader的用法示例。


在下文中一共展示了StringReader.ReadToFirstChar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Parse

        /// <summary>
        /// Returns parsed IMAP SEARCH <b>sequence-set</b> key.
        /// </summary>
        /// <param name="r">String reader.</param>
        /// <returns>Returns parsed IMAP SEARCH <b>sequence-set</b> key.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when parsing fails.</exception>
        internal static IMAP_Search_Key_SeqSet Parse(StringReader r)
        {
            if(r == null){
                throw new ArgumentNullException("r");
            }

            r.ReadToFirstChar();
            string value = r.QuotedReadToDelimiter(' ');
            if(value == null){
                throw new ParseException("Parse error: Invalid 'sequence-set' value.");
            }
            
            try{
                return new IMAP_Search_Key_SeqSet(IMAP_t_SeqSet.Parse(value));
            }
            catch{
                throw new ParseException("Parse error: Invalid 'sequence-set' value.");
            }
        }
开发者ID:CivilPol,项目名称:LumiSoft.Net,代码行数:26,代码来源:IMAP_Search_Key_SeqSet.cs

示例2: Parse

        /// <summary>
        /// Returns parsed IMAP SEARCH <b>UID (sequence set)</b> key.
        /// </summary>
        /// <param name="r">String reader.</param>
        /// <returns>Returns parsed IMAP SEARCH <b>UID (sequence set)</b> key.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when parsing fails.</exception>
        internal static IMAP_Search_Key_Uid Parse(StringReader r)
        {
            if(r == null){
                throw new ArgumentNullException("r");
            }

            string word = r.ReadWord();
            if(!string.Equals(word,"UID",StringComparison.InvariantCultureIgnoreCase)){
                throw new ParseException("Parse error: Not a SEARCH 'UID' key.");
            }
            r.ReadToFirstChar();
            string value = r.QuotedReadToDelimiter(' ');
            if(value == null){
                throw new ParseException("Parse error: Invalid 'UID' value.");
            }
            
            try{
                return new IMAP_Search_Key_Uid(IMAP_t_SeqSet.Parse(value));
            }
            catch{
                throw new ParseException("Parse error: Invalid 'UID' value.");
            }
        }
开发者ID:iraychen,项目名称:LumiSoft.Net,代码行数:30,代码来源:IMAP_Search_Key_Uid.cs

示例3: FETCH


//.........这里部分代码省略.........

            IMAP_t_SeqSet seqSet = null;
            try{                
                seqSet = IMAP_t_SeqSet.Parse(parts[0]);
            }
            catch{
                m_pResponseSender.SendResponseAsync(new IMAP_r_ServerStatus(cmdTag,"BAD","Error in arguments: Invalid 'sequence-set' value."));

                return;
            }

            #region Parse data-items

            List<IMAP_t_Fetch_i> dataItems     = new List<IMAP_t_Fetch_i>();
            bool                 msgDataNeeded = false;

            // Remove parenthesizes.
            string dataItemsString = parts[1].Trim();
            if(dataItemsString.StartsWith("(") && dataItemsString.EndsWith(")")){
                dataItemsString = dataItemsString.Substring(1,dataItemsString.Length - 2).Trim();
            }

            // Replace macros.
            dataItemsString = dataItemsString.Replace("ALL","FLAGS INTERNALDATE RFC822.SIZE ENVELOPE");
            dataItemsString = dataItemsString.Replace("FAST","FLAGS INTERNALDATE RFC822.SIZE"); 
            dataItemsString = dataItemsString.Replace("FULL","FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY");

            StringReader r = new StringReader(dataItemsString);

            IMAP_Fetch_DataType fetchDataType = IMAP_Fetch_DataType.MessageHeader;

            // Parse data-items.
            while(r.Available > 0){
                r.ReadToFirstChar();

                #region BODYSTRUCTURE

                if(r.StartsWith("BODYSTRUCTURE",false)){
                    r.ReadWord();
                    dataItems.Add(new IMAP_t_Fetch_i_BodyStructure());
                    msgDataNeeded = true;
                    if(fetchDataType != IMAP_Fetch_DataType.FullMessage){
                        fetchDataType = IMAP_Fetch_DataType.MessageStructure;
                    }
                }

                #endregion

                #region BODY[<section>]<<partial>> and BODY.PEEK[<section>]<<partial>>

                else if(r.StartsWith("BODY[",false) || r.StartsWith("BODY.PEEK[",false)){
                    bool peek = r.StartsWith("BODY.PEEK[",false);
                    r.ReadWord();

                    #region Parse <section>

                    string section = r.ReadParenthesized();
                                                                            
                    // Full message wanted.
                    if(string.IsNullOrEmpty(section)){
                        fetchDataType = IMAP_Fetch_DataType.FullMessage;
                    }
                    else{
                        // Left-side part-items must be numbers, only last one may be (HEADER,HEADER.FIELDS,HEADER.FIELDS.NOT,MIME,TEXT).
                    
                        StringReader rSection = new StringReader(section);
开发者ID:MichaelChansn,项目名称:Lumisoft.Net,代码行数:67,代码来源:IMAP_Session.cs

示例4: APPEND

        private void APPEND(string cmdTag,string cmdText)
        {
            /* RFC 3501 6.3.11. APPEND Command.
                Arguments:  mailbox name
                            OPTIONAL flag parenthesized list
                            OPTIONAL date/time string
                            message literal

                Responses:  no specific responses for this command

                Result:     OK - append completed
                            NO - append error: can't append to that mailbox, error
                                 in flags or date/time or message text
                            BAD - command unknown or arguments invalid

                The APPEND command appends the literal argument as a new message
                to the end of the specified destination mailbox.  This argument
                SHOULD be in the format of an [RFC-2822] message.  8-bit
                characters are permitted in the message.  A server implementation
                that is unable to preserve 8-bit data properly MUST be able to
                reversibly convert 8-bit APPEND data to 7-bit using a [MIME-IMB]
                content transfer encoding.

                    Note: There MAY be exceptions, e.g., draft messages, in
                    which required [RFC-2822] header lines are omitted in
                    the message literal argument to APPEND.  The full
                    implications of doing so MUST be understood and
                    carefully weighed.

                If a flag parenthesized list is specified, the flags SHOULD be set
                in the resulting message; otherwise, the flag list of the
                resulting message is set to empty by default.  In either case, the
                Recent flag is also set.

                If a date-time is specified, the internal date SHOULD be set in
                the resulting message; otherwise, the internal date of the
                resulting message is set to the current date and time by default.

                If the append is unsuccessful for any reason, the mailbox MUST be
                restored to its state before the APPEND attempt; no partial
                appending is permitted.

                If the destination mailbox does not exist, a server MUST return an
                error, and MUST NOT automatically create the mailbox.  Unless it
                is certain that the destination mailbox can not be created, the
                server MUST send the response code "[TRYCREATE]" as the prefix of
                the text of the tagged NO response.  This gives a hint to the
                client that it can attempt a CREATE command and retry the APPEND
                if the CREATE is successful.

                If the mailbox is currently selected, the normal new message
                actions SHOULD occur.  Specifically, the server SHOULD notify the
                client immediately via an untagged EXISTS response.  If the server
                does not do so, the client MAY issue a NOOP command (or failing
                that, a CHECK command) after one or more APPEND commands.

                Example:    C: A003 APPEND saved-messages (\Seen) {310}
                            S: + Ready for literal data
                            C: Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST)
                            C: From: Fred Foobar <[email protected]>
                            C: Subject: afternoon meeting
                            C: To: [email protected]
                            C: Message-Id: <[email protected]>
                            C: MIME-Version: 1.0
                            C: Content-Type: TEXT/PLAIN; CHARSET=US-ASCII
                            C:
                            C: Hello Joe, do you think we can meet at 3:30 tomorrow?
                            C:
                            S: A003 OK APPEND completed

                    Note: The APPEND command is not used for message delivery,
                    because it does not provide a mechanism to transfer [SMTP]
                    envelope information.
            */

            if(!this.IsAuthenticated){
                m_pResponseSender.SendResponseAsync(new IMAP_r_ServerStatus(cmdTag,"NO","Authentication required."));

                return;
            }

            // Store start time
			long startTime = DateTime.Now.Ticks;

            #region Parse arguments

            StringReader r = new StringReader(cmdText);
            r.ReadToFirstChar();
            string folder = null;
            if(r.StartsWith("\"")){
                folder = IMAP_Utils.DecodeMailbox(r.ReadWord());
            }
            else{
                folder = IMAP_Utils.DecodeMailbox(r.QuotedReadToDelimiter(' '));
            }
            r.ReadToFirstChar();
            List<string> flags = new List<string>();
            if(r.StartsWith("(")){                
                foreach(string f in r.ReadParenthesized().Split(' ')){
                    if(f.Length > 0 && !flags.Contains(f.Substring(1))){
//.........这里部分代码省略.........
开发者ID:MichaelChansn,项目名称:Lumisoft.Net,代码行数:101,代码来源:IMAP_Session.cs

示例5: ParseKey

        /// <summary>
        /// Parses one search key or search key group.
        /// </summary>
        /// <param name="r">String reader.</param>
        /// <returns>Returns one parsed search key or search key group.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>r</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when parsing fails.</exception>
        internal static IMAP_Search_Key ParseKey(StringReader r)
        {
            if(r == null){
                throw new ArgumentNullException("r");
            }

            r.ReadToFirstChar();

            // Keys group
            if(r.StartsWith("(",false)){
                return IMAP_Search_Key_Group.Parse(new StringReader(r.ReadParenthesized()));
            }
            // ANSWERED
            else if(r.StartsWith("ANSWERED",false)){
                return IMAP_Search_Key_Answered.Parse(r);
            }
            // BCC
            else if(r.StartsWith("BCC",false)){
                return IMAP_Search_Key_Bcc.Parse(r);
            }
            // BEFORE
            else if(r.StartsWith("BEFORE",false)){
                return IMAP_Search_Key_Before.Parse(r);
            }
            // BODY
            else if(r.StartsWith("BODY",false)){
                return IMAP_Search_Key_Body.Parse(r);
            }
            // CC
            else if(r.StartsWith("CC",false)){
                return IMAP_Search_Key_Cc.Parse(r);
            }
            // DELETED
            else if(r.StartsWith("DELETED",false)){
                return IMAP_Search_Key_Deleted.Parse(r);
            }
            // DRAFT
            else if(r.StartsWith("DRAFT",false)){
                return IMAP_Search_Key_Draft.Parse(r);
            }
            // FLAGGED
            else if(r.StartsWith("FLAGGED",false)){
                return IMAP_Search_Key_Flagged.Parse(r);
            }
            // FROM
            else if(r.StartsWith("FROM",false)){
                return IMAP_Search_Key_From.Parse(r);
            }
            // HEADER
            else if(r.StartsWith("HEADER",false)){
                return IMAP_Search_Key_Header.Parse(r);
            }
            // KEYWORD
            else if(r.StartsWith("KEYWORD",false)){
                return IMAP_Search_Key_Keyword.Parse(r);
            }
            // LARGER
            else if(r.StartsWith("LARGER",false)){
                return IMAP_Search_Key_Larger.Parse(r);
            }
            // NEW
            else if(r.StartsWith("NEW",false)){
                return IMAP_Search_Key_New.Parse(r);
            }
            // NOT
            else if(r.StartsWith("NOT",false)){
                return IMAP_Search_Key_Not.Parse(r);
            }
            // OLD
            else if(r.StartsWith("OLD",false)){
                return IMAP_Search_Key_Old.Parse(r);
            }
            // ON
            else if(r.StartsWith("ON",false)){
                return IMAP_Search_Key_On.Parse(r);
            }
            // OR
            else if(r.StartsWith("OR",false)){
                return IMAP_Search_Key_Or.Parse(r);
            }
            // RECENT
            else if(r.StartsWith("RECENT",false)){
                return IMAP_Search_Key_Recent.Parse(r);
            }
            // SEEN
            else if(r.StartsWith("SEEN",false)){
                return IMAP_Search_Key_Seen.Parse(r);
            }
            // SENTBEFORE
            else if(r.StartsWith("SENTBEFORE",false)){
                return IMAP_Search_Key_SentBefore.Parse(r);
            }
            // SENTON
//.........这里部分代码省略.........
开发者ID:nbhopson,项目名称:QMail,代码行数:101,代码来源:IMAP_Search_Key.cs

示例6: ReadData

        /// <summary>
        /// Reads IMAP string(string-literal,quoted-string,NIL) and remaining FETCH line if needed.
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">Fetch line reader.</param>
        /// <param name="callback">Fetch completion callback.</param>
        /// <param name="stream">Stream where to store readed data.</param>
        /// <returns>Returns true if completed asynchronously or false if completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b>,<b>callback</b> or <b>stream</b> is null reference.</exception>
        private bool ReadData(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback,Stream stream)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            r.ReadToFirstChar();

            // We don't have data.
            if(r.StartsWith("NIL",false)){
                // Eat NIL.
                r.ReadWord();

                return false;
            }
            // Data value is returned as string-literal.
            else if(r.StartsWith("{",false)){
                IMAP_Client.ReadStringLiteralAsyncOP op = new IMAP_Client.ReadStringLiteralAsyncOP(stream,Convert.ToInt32(r.ReadParenthesized()));
                op.CompletedAsync += delegate(object sender,EventArgs<IMAP_Client.ReadStringLiteralAsyncOP> e){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));
                        }
                        else{
                            // Read next fetch line completed synchronously.
                            if(!ReadNextFetchLine(imap,r,callback)){
                                ParseDataItems(imap,r,callback);
                            }
                        }
                    }
                    catch(Exception x){
                        callback(this,new EventArgs<Exception>(x));
                    }
                    finally{
                        op.Dispose();
                    }
                };

                // Read string literal completed sync.
                if(!imap.ReadStringLiteralAsync(op)){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));

                            return true;
                        }
                        else{
                            // Read next fetch line completed synchronously.
                            if(!ReadNextFetchLine(imap,r,callback)){
                                return false;
                            }
                            else{
                                return true;
                            }
                        }
                    }
                    finally{
                        op.Dispose();
                    }
                }
                // Read string literal completed async.
                else{
                    return true;
                }
            }
            // Data is quoted-string.
            else{
                byte[] data = Encoding.UTF8.GetBytes(r.ReadWord());
                stream.Write(data,0,data.Length);

                return false;
            }
        }
开发者ID:nbhopson,项目名称:QMail,代码行数:93,代码来源:IMAP_r_u_Fetch.cs

示例7: ParseDataItems

        /// <summary>
        /// Starts parsing fetch data-items,
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">Fetch line reader.</param>
        /// <param name="callback">Callback to be called when parsing completes.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b> or <b>callback</b> is null reference.</exception>
        private void ParseDataItems(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            /* RFC 3501 7.4.2. FETCH Response.
                Example:    S: * 23 FETCH (FLAGS (\Seen) RFC822.SIZE 44827)
            */

            while(true){
                r.ReadToFirstChar();

                #region BODY[]

                if(r.StartsWith("BODY[",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        BODY[<section>]<<origin octet>>
                         A string expressing the body contents of the specified section.
                         The string SHOULD be interpreted by the client according to the
                         content transfer encoding, body type, and subtype.

                         If the origin octet is specified, this string is a substring of
                         the entire body contents, starting at that origin octet.  This
                         means that BODY[]<0> MAY be truncated, but BODY[] is NEVER
                         truncated.

                            Note: The origin octet facility MUST NOT be used by a server
                            in a FETCH response unless the client specifically requested
                            it by means of a FETCH of a BODY[<section>]<<partial>> data
                            item.

                         8-bit textual data is permitted if a [CHARSET] identifier is
                         part of the body parameter parenthesized list for this section.
                         Note that headers (part specifiers HEADER or MIME, or the
                         header portion of a MESSAGE/RFC822 part), MUST be 7-bit; 8-bit
                         characters are not permitted in headers.  Note also that the
                         [RFC-2822] delimiting blank line between the header and the
                         body is not affected by header line subsetting; the blank line
                         is always included as part of header data, except in the case
                         of a message which has no body and no blank line.

                         Non-textual data such as binary data MUST be transfer encoded
                         into a textual form, such as BASE64, prior to being sent to the
                         client.  To derive the original binary data, the client MUST
                         decode the transfer encoded string.
                    */

                    // Eat BODY word.
                    r.ReadWord();

                    // Read body-section.
                    string section = r.ReadParenthesized();

                    // Read origin if any.
                    int offset = -1;
                    if(r.StartsWith("<")){
                        offset = Convert.ToInt32(r.ReadParenthesized().Split(' ')[0]);
                    }

                    IMAP_t_Fetch_r_i_Body dataItem = new IMAP_t_Fetch_r_i_Body(section,offset,new MemoryStreamEx(32000));
                    m_pDataItems.Add(dataItem);

                    // Raise event, allow user to specify store stream.
                    IMAP_Client_e_FetchGetStoreStream eArgs = new IMAP_Client_e_FetchGetStoreStream(this,dataItem);
                    imap.OnFetchGetStoreStream(eArgs);
                    // User specified own stream, use it.
                    if(eArgs.Stream != null){
                        dataItem.Stream.Dispose();
                        dataItem.SetStream(eArgs.Stream);
                    }

                    // Read data will complete async and will continue data-items parsing, exit this method.
                    if(ReadData(imap,r,callback,dataItem.Stream)){
                        return;
                    }
                    // Continue processing.
                    //else{
                }

                #endregion

                #region BODY

                else if(r.StartsWith("BODY ",false)){
                    //IMAP_t_Fetch_r_i_BodyS
                }
//.........这里部分代码省略.........
开发者ID:nbhopson,项目名称:QMail,代码行数:101,代码来源:IMAP_r_u_Fetch.cs

示例8: ParseAsync

        /// <summary>
        /// Starts parsing FETCH response.
        /// </summary>
        /// <param name="imap">IMAP cleint.</param>
        /// <param name="line">Initial FETCH response line.</param>
        /// <param name="callback">Callback to be called when fetch completed.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>line</b> or <b>callback</b> is null reference.</exception>
        internal void ParseAsync(IMAP_Client imap,string line,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(line == null){
                throw new ArgumentNullException("line");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            /* RFC 3501 7.4.2. FETCH Response.
                Example:    S: * 23 FETCH (FLAGS (\Seen) RFC822.SIZE 44827)
            */

            StringReader r = new StringReader(line);

            // Eat '*'
            r.ReadWord();
            // Parse seqNo
            m_MsgSeqNo = Convert.ToInt32(r.ReadWord());
            // Eat 'FETCH'
            r.ReadWord();
            // Eat '(', if list of fetch data-items.
            r.ReadToFirstChar();
            if(r.StartsWith("(")){
                r.ReadSpecifiedLength(1);
            }

            ParseDataItems(imap,r,callback);
        }
开发者ID:nbhopson,项目名称:QMail,代码行数:39,代码来源:IMAP_r_u_Fetch.cs

示例9: Fetch


//.........这里部分代码省略.........
                    {
                        sequenceSet.Parse(args[0], m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID);
                    }
                }
                else
                {
                    sequenceSet.Parse(args[0], m_pSelectedFolder.Messages.Count);
                }
            }
            // This isn't valid sequnce-set value
            catch
            {
                this.TcpStream.WriteLine(string.Format("{0} BAD Invalid <sequnce-set> value '{1}' Syntax: {{<command-tag> FETCH <sequnce-set> (<fetch-keys>)}}!", cmdTag, args[0]));
                return;
            }

            // Replace macros
            string fetchItems = args[1].ToUpper();
            fetchItems = fetchItems.Replace("ALL", "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE");
            fetchItems = fetchItems.Replace("FAST", "FLAGS INTERNALDATE RFC822.SIZE");
            fetchItems = fetchItems.Replace("FULL", "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY");

            // If UID FETCH and no UID, we must implicity add it, it's required 
            if (uidFetch && fetchItems.ToUpper().IndexOf("UID") == -1)
            {
                fetchItems += " UID";
            }

            // Start parm parsing from left to end in while loop while params parsed or bad param found
            ArrayList fetchFlags = new ArrayList();
            StringReader argsReader = new StringReader(fetchItems.Trim());
            while (argsReader.Available > 0)
            {
                argsReader.ReadToFirstChar();

                #region BODYSTRUCTURE

                // BODYSTRUCTURE
                if (argsReader.StartsWith("BODYSTRUCTURE"))
                {
                    argsReader.ReadSpecifiedLength("BODYSTRUCTURE".Length);

                    fetchFlags.Add(new object[] { "BODYSTRUCTURE" });
                    messageItems |= IMAP_MessageItems_enum.BodyStructure;
                }

                #endregion

                #region BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>>

                // BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>>
                else if (argsReader.StartsWith("BODY"))
                {
                    // Remove BODY
                    argsReader.ReadSpecifiedLength("BODY".Length);

                    bool peek = false;
                    // BODY.PEEK
                    if (argsReader.StartsWith(".PEEK"))
                    {
                        // Remove .PEEK
                        argsReader.ReadSpecifiedLength(".PEEK".Length);

                        peek = true;
                    }
开发者ID:haoasqui,项目名称:ONLYOFFICE-Server,代码行数:66,代码来源:IMAP_Session.cs

示例10: ParseDate


//.........这里部分代码省略.........
            StringReader s = new StringReader(date);

            //--- Pase date --------------------------------------------------------------------//
            try{
                day = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
            }
            catch{
                throw new Exception("Invalid date value '" + date + "', invalid day value !");
            }

            try{
                month = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
            }
            catch{
                throw new Exception("Invalid date value '" + date + "', invalid month value !");
            }

            try{
                year = Convert.ToInt32(s.ReadWord(true,new char[]{'.','-',' '},true));
            }
            catch{
                throw new Exception("Invalid date value '" + date + "', invalid year value !");
            }
            //----------------------------------------------------------------------------------//

            //--- Parse time -------------------------------------------------------------------//
            // Time is optional, so parse it if its included.
            if(s.Available > 0){
                try{
                    hour = Convert.ToInt32(s.ReadWord(true,new char[]{':'},true));
                }
                catch{
                    throw new Exception("Invalid date value '" + date + "', invalid hour value !");
                }

                try{
                    minute = Convert.ToInt32(s.ReadWord(true,new char[]{':'},false));
                }
                catch{
                    throw new Exception("Invalid date value '" + date + "', invalid minute value !");
                }

                s.ReadToFirstChar();
                if(s.StartsWith(":")){
                    s.ReadSpecifiedLength(1);
                    try{
                        string secondString = s.ReadWord(true,new char[]{' '},true);
                        // Milli seconds specified, remove them.
                        if(secondString.IndexOf('.') > -1){
                            secondString = secondString.Substring(0,secondString.IndexOf('.'));
                        }
                        second = Convert.ToInt32(secondString);
                    }
                    catch{
                        throw new Exception("Invalid date value '" + date + "', invalid second value !");
                    }
                }

                s.ReadToFirstChar();
                if(s.Available > 3){
                    string timezone = s.SourceString.Replace(":","");
                    if(timezone.StartsWith("+") || timezone.StartsWith("-")){
                        bool utc_add_time = timezone.StartsWith("+");

                        // Remove +/- sign
                        timezone = timezone.Substring(1);

                        // padd time zone to 4 symbol. For example 200, will be 0200.
                        while(timezone.Length < 4){
                            timezone = "0" + timezone;
                        }

                        try{
                            // time zone format hours|minutes
                            int h = Convert.ToInt32(timezone.Substring(0,2));
                            int m = Convert.ToInt32(timezone.Substring(2));

                            if(utc_add_time){
                                zoneMinutes = 0 - ((h * 60) + m);
                            }
                            else{
                                zoneMinutes = (h * 60) + m;
                            }
                        }
                        catch{ // Just skip time zone, if can't parse
                        }
                    }
                }
            }
            //---------------------------------------------------------------------------------//

            // Convert time to UTC
            if(hour != -1 && minute != -1 && second != -1){
                DateTime d = new DateTime(year,month,day,hour,minute,second).AddMinutes(zoneMinutes);
                return new DateTime(d.Year,d.Month,d.Day,d.Hour,d.Minute,d.Second,DateTimeKind.Utc).ToLocalTime();
            }
            else{
                return new DateTime(year,month,day);
            }
        }
开发者ID:janemiceli,项目名称:authenticated_mail_server,代码行数:101,代码来源:MimeUtils.cs

示例11: ReadString

        /// <summary>
        /// Reads IMAP string-literal/string/astring/nstring/utf8-quoted from string reader.
        /// </summary>
        /// <param name="reader">String reader.</param>
        /// <returns>Returns IMAP string.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception>
        public static string ReadString(StringReader reader)
        {
            if(reader == null){
                throw new ArgumentNullException("reader");
            }

            reader.ReadToFirstChar();

            // We have string-literal.
            if(reader.SourceString.StartsWith("{")){
                int literalSize = Convert.ToInt32(reader.ReadParenthesized());
                // Literal has CRLF ending, skip it.
                reader.ReadSpecifiedLength(2);
                                                
                return reader.ReadSpecifiedLength(literalSize);
            }
            // utf8-quoted old rfc 5738
            else if(reader.StartsWith("*\"")){
                reader.ReadSpecifiedLength(1);

                return reader.ReadWord();
            }
            // string/astring/nstring
            else{
                string word = reader.ReadWord();
                
                // nstring
                if(string.Equals(word,"NIL",StringComparison.InvariantCultureIgnoreCase)){
                    return null;
                }

                return word;
            }
        }
开发者ID:DJGosnell,项目名称:LumiSoft.Net,代码行数:40,代码来源:IMAP_Utils.cs

示例12: DecodeWords

        /// <summary>
        /// Decodes "encoded-word"'s from the specified text. For more information see RFC 2047.
        /// </summary>
        /// <param name="text">Text to decode.</param>
        /// <returns>Returns decoded text.</returns>
        public static string DecodeWords(string text)
        {
            if(text == null){
                return null;
            }

            /* RFC 2047 2. Syntax of encoded-words.
                An 'encoded-word' is defined by the following ABNF grammar.  The
                notation of RFC 822 is used, with the exception that white space
                characters MUST NOT appear between components of an 'encoded-word'.

                encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
                charset      = token    ; see section 3
                encoding     = token    ; see section 4
                token        = 1*<Any CHAR except SPACE, CTLs, and especials>
                especials    = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "
                               <"> / "/" / "[" / "]" / "?" / "." / "="
                encoded-text = 1*<Any printable ASCII character other than "?" or SPACE>
                                       ; (but see "Use of encoded-words in message headers", section 5)

                Both 'encoding' and 'charset' names are case-independent.  Thus the
                charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the
                encoding named "Q" may be spelled either "Q" or "q".

                An 'encoded-word' may not be more than 75 characters long, including
                'charset', 'encoding', 'encoded-text', and delimiters.  If it is
                desirable to encode more text than will fit in an 'encoded-word' of
                75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may
                be used.
              
                IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's
                by an RFC 822 parser.  As a consequence, unencoded white space
                characters (such as SPACE and HTAB) are FORBIDDEN within an
                'encoded-word'.  For example, the character sequence

                =?iso-8859-1?q?this is some text?=

                would be parsed as four 'atom's, rather than as a single 'atom' (by
                an RFC 822 parser) or 'encoded-word' (by a parser which understands
                'encoded-words').  The correct way to encode the string "this is some
                text" is to encode the SPACE characters as well, e.g.

                =?iso-8859-1?q?this=20is=20some=20text?=
            */

            StringReader  r      = new StringReader(text);
            StringBuilder retVal = new StringBuilder();

            // We need to loop all words, if encoded word, decode it, othwerwise just append to return value.
            bool lastIsEncodedWord = false;
            while(r.Available > 0){
                string whiteSpaces = r.ReadToFirstChar();

                // Probably is encoded-word, we try to parse it.
                if(r.StartsWith("=?") && r.SourceString.IndexOf("?=") > -1){
                    StringBuilder encodedWord = new StringBuilder();
                    string        decodedWord = null;

                    try{
                        // NOTE: We can't read encoded word and then split !!!, we need to read each part.
                    
                        // Remove =?
                        encodedWord.Append(r.ReadSpecifiedLength(2));

                        // Read charset
                        string charset = r.QuotedReadToDelimiter('?');
                        encodedWord.Append(charset + "?");

                        // Read encoding
                        string encoding = r.QuotedReadToDelimiter('?');
                        encodedWord.Append(encoding + "?");

                        // Read text
                        string encodedText = r.QuotedReadToDelimiter('?');
                        encodedWord.Append(encodedText + "?");

                        // We must have remaining '=' here
                        if(r.StartsWith("=")){
                            encodedWord.Append(r.ReadSpecifiedLength(1));

                            Encoding c = Encoding.GetEncoding(charset);
                            if(encoding.ToLower() == "q"){
                                decodedWord = Core.QDecode(c,encodedText);
                            }
                            else if(encoding.ToLower() == "b"){
                                decodedWord = c.GetString(Core.Base64Decode(Encoding.Default.GetBytes(encodedText)));
                            }
                        }
                    }
                    catch{
                        // Not encoded-word or contains unknwon charset/encoding, so leave
                        // encoded-word as is.
                    }

                    /* RFC 2047 6.2.
//.........这里部分代码省略.........
开发者ID:CivilPol,项目名称:LumiSoft.Net,代码行数:101,代码来源:MimeUtils.cs

示例13: FetchMessages


//.........这里部分代码省略.........
                LogAddRead(args.BytesInBuffer, line);

                // We have un-tagged resposne.
                if (line.StartsWith("*"))
                {
                    if (IsStatusResponse(line))
                    {
                        ProcessStatusResponse(line);
                    }
                    else
                    {
                        int no = 0;
                        int uid = 0;
                        int size = 0;
                        byte[] data = null;
                        IMAP_MessageFlags flags = IMAP_MessageFlags.Recent;
                        string envelope = "";
                        string bodystructure = "";
                        string internalDate = "";

                        // Remove *
                        line = RemoveCmdTag(line);

                        // Get message number
                        no = Convert.ToInt32(line.Substring(0, line.IndexOf(" ")));

                        // Get rid of FETCH  and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...)
                        line = line.Substring(line.IndexOf("FETCH (") + 7);

                        StringReader r = new StringReader(line);
                        // Loop fetch result fields
                        while (r.Available > 0)
                        {
                            r.ReadToFirstChar();

                            // Fetch command closing ) parenthesis
                            if (r.SourceString == ")")
                            {
                                break;
                            }

                            #region UID <value>

                            // UID <value>
                            else if (r.StartsWith("UID", false))
                            {
                                // Remove UID word from reply
                                r.ReadSpecifiedLength("UID".Length);
                                r.ReadToFirstChar();

                                // Read <value>
                                string word = r.ReadWord();
                                if (word == null)
                                {
                                    throw new Exception("IMAP server didn't return UID <value> !");
                                }
                                else
                                {
                                    uid = Convert.ToInt32(word);
                                }
                            }

                            #endregion

                            #region RFC822.SIZE <value>
开发者ID:Klaudit,项目名称:inbox2_desktop,代码行数:66,代码来源:IMAP_Client.cs

示例14: GetList


//.........这里部分代码省略.........
                if(!response[0].StartsWith("1")){
                    throw new FTP_ClientException(response[0]);
                }

                MemoryStream ms = new MemoryStream();
                m_pDataConnection.ReadAll(ms);

                response = ReadResponse();
                if(!response[0].StartsWith("2")){
                    throw new FTP_ClientException(response[0]);
                }

                ms.Position = 0;
                SmartStream listStream =  new SmartStream(ms,true);

                string[] winDateFormats = new string[]{"M-d-yy h:mmtt"};
                string[] unixFormats    = new string[]{"MMM d H:mm","MMM d yyyy"};

                SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[8000],SizeExceededAction.JunkAndThrowException);
                while(true){
                    listStream.ReadLine(args,false);
                    if(args.Error != null){
                        throw args.Error;
                    }
                    else if(args.BytesInBuffer == 0){
                        break;
                    }
                    string line = args.LineUtf8;

                    // Dedect listing.
                    string listingType = "unix";
                    if(line != null){
                        StringReader r = new StringReader(line);
                        DateTime modified;
                        if(DateTime.TryParseExact(r.ReadWord() + " " + r.ReadWord(),new string[]{"MM-dd-yy hh:mmtt"},System.Globalization.DateTimeFormatInfo.InvariantInfo,System.Globalization.DateTimeStyles.None,out modified)){
                            listingType = "win";
                        }
                    }

                    try{
                        // Windows listing.
                        if(listingType == "win"){
                            // MM-dd-yy hh:mm <DIR> directoryName
                            // MM-dd-yy hh:mm size  fileName

                            StringReader r = new StringReader(line);
                            // Read date
                            DateTime modified = DateTime.ParseExact(r.ReadWord() + " " + r.ReadWord(),winDateFormats,System.Globalization.DateTimeFormatInfo.InvariantInfo,System.Globalization.DateTimeStyles.None);

                            r.ReadToFirstChar();
                            // We have directory.
                            if(r.StartsWith("<dir>",false)){
                                r.ReadSpecifiedLength(5);
                                r.ReadToFirstChar();

                                retVal.Add(new FTP_ListItem(r.ReadToEnd(),0,modified,true));
                            }
                            // We have file
                            else{
                                // Read file size
                                long size = Convert.ToInt64(r.ReadWord());
                                r.ReadToFirstChar();

                                retVal.Add(new FTP_ListItem(r.ReadToEnd(),size,modified,false));
                            }
                        }
                        // Unix listing
                        else{
                            // "d"directoryAtttributes xx xx xx 0 MMM d HH:mm/yyyy directoryName
                            // fileAtttributes xx xx xx fileSize MMM d HH:mm/yyyy fileName

                            StringReader r = new StringReader(line);
                            string attributes = r.ReadWord();
                            r.ReadWord();
                            r.ReadWord();
                            r.ReadWord();
                            long size = Convert.ToInt64(r.ReadWord());
                            DateTime modified = DateTime.ParseExact(r.ReadWord() + " " + r.ReadWord() + " " + r.ReadWord(),unixFormats,System.Globalization.DateTimeFormatInfo.InvariantInfo,System.Globalization.DateTimeStyles.None);
                            r.ReadToFirstChar();
                            string name = r.ReadToEnd();
                            if(name != "." && name != ".."){
                                if(attributes.StartsWith("d")){
                                    retVal.Add(new FTP_ListItem(name,0,modified,true));
                                }
                                else{
                                    retVal.Add(new FTP_ListItem(name,size,modified,false));
                                }
                            }
                        }
                    }
                    catch{
                        // Skip unknown entries.
                    }
                }
            }

            #endregion

            return retVal.ToArray();
        }
开发者ID:andreikalatsei,项目名称:milskype,代码行数:101,代码来源:FTP_Client.cs

示例15: ReadString

        /// <summary>
        /// Reads IMAP string/astring/nstring/utf8-quoted from string reader.
        /// </summary>
        /// <param name="reader">String reader.</param>
        /// <returns>Returns IMAP string.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>reader</b> is null reference.</exception>
        internal static string ReadString(StringReader reader)
        {
            if(reader == null){
                throw new ArgumentNullException("reader");
            }

            reader.ReadToFirstChar();

            // utf8-quoted
            if(reader.StartsWith("*\"")){
                reader.ReadSpecifiedLength(1);

                return reader.ReadWord();
            }
            // string/astring/nstring
            else{
                string word = reader.ReadWord();

                // nstring
                if(string.Equals(word,"NIL",StringComparison.InvariantCultureIgnoreCase)){
                    return null;
                }

                return word;
            }
        }
开发者ID:ChuckLafferty,项目名称:bugnet,代码行数:32,代码来源:IMAP_Utils.cs


注:本文中的System.IO.StringReader.ReadToFirstChar方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。