Click here to Skip to main content
15,885,309 members
Articles / Programming Languages / C#

A C# Implementation of Mime De/encode

Rate me:
Please Sign up or sign in to vote.
4.00/5 (16 votes)
21 Aug 2005CPOL 150.8K   4.2K   38  
A C# implementation of Mime de/encode
using System;

namespace MIME
{
	/// <summary>
	/// 
	/// </summary>
	public class MimeCode
	{
		public MimeCode()
		{
			// 
			// TODO: Add constructor logic here
			//
		}

		private string m_charset;

		public string Charset
		{
			get{ return m_charset; }
			set{ this.m_charset = value; }
		}

		public virtual byte[] DecodeToBytes(string s)
		{
			if(s == null)
				throw new ArgumentNullException();

			if(m_charset != null)
			{
				return System.Text.Encoding.GetEncoding(m_charset).GetBytes(s);
			}
			else
			{
				m_charset = System.Text.Encoding.Default.BodyName;
				return System.Text.Encoding.Default.GetBytes(s);
			}
		}

		public virtual string DecodeToString(string s)
		{
			byte[] b = DecodeToBytes(s);
			if(m_charset != null)
			{
				return System.Text.Encoding.GetEncoding(m_charset).GetString(b);
			}
			else
			{
				m_charset = System.Text.Encoding.Default.BodyName;
				return System.Text.Encoding.Default.GetString(b);
			}
		}

		public virtual string EncodeFromBytes(byte[] inArray, int offset, int length)
		{
			if(inArray == null)
				throw new ArgumentNullException();

			if(m_charset != null)
			{
				return System.Text.Encoding.GetEncoding(m_charset).GetString(inArray, offset, length);
			}
			else
			{
				m_charset = System.Text.Encoding.Default.BodyName;
				return System.Text.Encoding.Default.GetString(inArray, offset, length);
			}
		}
		
		public string EncodeFromBytes(byte[] inArray)
		{
			return EncodeFromBytes(inArray, 0, inArray.Length);
		}

		public virtual string EncodeFromString(string s)
		{
			if(s == null)
				throw new ArgumentNullException();

			byte[] inArray;
			if(m_charset != null)
			{
				inArray = System.Text.Encoding.GetEncoding(m_charset).GetBytes(s);
			}
			else
			{
				m_charset = System.Text.Encoding.Default.BodyName;
				inArray = System.Text.Encoding.Default.GetBytes(s);
			}
			return EncodeFromBytes(inArray);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
China China
I think I have to start coding my life now...Smile | :)

Comments and Discussions