小鬼之家

流浪,游走于文明与原始之间. 关注底层技术,实现美好生活。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Cvv.Components
{
    
public class Serializer
    
{
        
public static readonly bool CanBinarySerialize;

        
static Serializer()
        
{
            SecurityPermission permission 
= new SecurityPermission(SecurityPermissionFlag.SerializationFormatter);
            
try
            
{
                permission.Demand();
                CanBinarySerialize 
= true;
            }

            
catch (SecurityException)
            
{
                CanBinarySerialize 
= false;
            }

        }


        
private Serializer()
        
{
        }


        
public static object ConvertFileToObject(string path, Type objectType)
        
{
            
object obj2 = null;
            
if ((path != null&& (path.Length > 0))
            
{
                
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                
{
                    obj2 
= new XmlSerializer(objectType).Deserialize(stream);
                    stream.Close();
                }

            }

            
return obj2;
        }


        
public static void ConvertFromNameValueCollection(NameValueCollection nvc, ref string keys, ref string values)
        
{
            ConvertFromNameValueCollection(nvc, 
ref keys, ref values, false);
        }


        
public static void ConvertFromNameValueCollection(NameValueCollection nvc, ref string keys, ref string values, bool allowEmptyStrings)
        
{
            
if ((nvc != null&& (nvc.Count != 0))
            
{
                StringBuilder builder 
= new StringBuilder();
                StringBuilder builder2 
= new StringBuilder();
                
int num = 0;
                
foreach (string text in nvc.AllKeys)
                
{
                    
if (text.IndexOf(':'!= -1)
                    
{
                        
throw new ArgumentException("ExtendedAttributes Key can not contain the character \":\"");
                    }

                    
string text2 = nvc[text];
                    
if ((allowEmptyStrings && (text2 != null)) || !TypeHelper.IsNullorEmpty(text2))
                    
{
                        builder.AppendFormat(
"{0}:S:{1}:{2}:", text, num, text2.Length);
                        builder2.Append(text2);
                        num 
+= text2.Length;
                    }

                }

                keys 
= builder.ToString();
                values 
= builder2.ToString();
            }

        }


        
public static object ConvertSOAPToObject(string xml, Type objType)
        
{
            MemoryStream serializationStream 
= null;
            
object obj2;
            
try
            
{
                IFormatter formatter 
= new SoapFormatter();
                serializationStream 
= new MemoryStream(Encoding.Default.GetBytes(xml));
                obj2 
= formatter.Deserialize(serializationStream);
            }

            
finally
            
{
                
if (serializationStream != null)
                
{
                    serializationStream.Close();
                }

            }

            
return obj2;
        }


        
public static byte[] ConvertToBytes(object objectToConvert)
        
{
            
byte[] buffer = null;
            
if (CanBinarySerialize)
            
{
                BinaryFormatter formatter 
= new BinaryFormatter();
                
using (MemoryStream serializationStream = new MemoryStream())
                
{
                    formatter.Serialize(serializationStream, objectToConvert);
                    serializationStream.Position 
= 0;
                    buffer 
= new byte[serializationStream.Length];
                    serializationStream.Read(buffer, 
0, buffer.Length);
                    serializationStream.Close();
                }

            }

            
return buffer;
        }


        
public static byte[] ConvertToBytes(string s)
        
{
            
return Convert.FromBase64String(s);
        }


        
public static NameValueCollection ConvertToNameValueCollection(string keys, string values)
        
{
            NameValueCollection values2 
= new NameValueCollection();
            
if (((keys != null&& (values != null)) && ((keys.Length > 0&& (values.Length > 0)))
            
{
                
char[] separator = new char[] ':' };
                
string[] textArray = keys.Split(separator);
                
for (int i = 0; i < (textArray.Length / 4); i++)
                
{
                    
int startIndex = int.Parse(textArray[(i * 4+ 2], CultureInfo.InvariantCulture);
                    
int length = int.Parse(textArray[(i * 4+ 3], CultureInfo.InvariantCulture);
                    
string text = textArray[i * 4];
                    
if (((textArray[(i * 4+ 1== "S"&& (startIndex >= 0)) && (values.Length >= (startIndex + length)))
                    
{
                        values2[text] 
= values.Substring(startIndex, length);
                    }

                }

            }

            
return values2;
        }


        
public static object ConvertToObject(byte[] byteArray)
        
{
            
object obj2 = null;
            
if ((CanBinarySerialize && (byteArray != null)) && (byteArray.Length > 0))
            
{
                BinaryFormatter formatter 
= new BinaryFormatter();
                
using (MemoryStream serializationStream = new MemoryStream())
                
{
                    serializationStream.Write(byteArray, 
0, byteArray.Length);
                    serializationStream.Position 
= 0;
                    
if (byteArray.Length > 4)
                    
{
                        obj2 
= formatter.Deserialize(serializationStream);
                    }

                    serializationStream.Close();
                }

            }

            
return obj2;
        }


        
public static object ConvertToObject(string xml, Type objectType)
        
{
            
object obj2 = null;
            
if (!TypeHelper.IsNullorEmpty(xml))
            
{
                
using (StringReader textReader = new StringReader(xml))
                
{
                    obj2 
= new XmlSerializer(objectType).Deserialize(textReader);
                    textReader.Close();
                }

            }

            
return obj2;
        }


        
public static object ConvertToObject(XmlNode node, Type objectType)
        
{
            
object obj2 = null;
            
if (node != null)
            
{
                
using (StringReader textReader = new StringReader(node.OuterXml))
                
{
                    obj2 
= new XmlSerializer(objectType).Deserialize(textReader);
                    textReader.Close();
                }

            }

            
return obj2;
        }


        
public static string ConvertToSOAPString(object obj)
        
{
            MemoryStream serializationStream 
= null;
            
string text;
            
try
            
{
                serializationStream 
= new MemoryStream();
                IFormatter formatter 
= new SoapFormatter();
                formatter.Serialize(serializationStream, obj);
                
int count = (int)serializationStream.Length;
                
byte[] buffer = new byte[count];
                serializationStream.Seek((
long)0, SeekOrigin.Begin);
                serializationStream.Read(buffer, 
0, count);
                UTF8Encoding encoding 
= new UTF8Encoding();
                text 
= encoding.GetString(buffer).Trim();
            }

            
finally
            
{
                
if (serializationStream != null)
                
{
                    serializationStream.Close();
                }

            }

            
return text;
        }


        
public static string ConvertToString(byte[] arr)
        
{
            
return Convert.ToBase64String(arr);
        }


        
public static string ConvertToString(object objectToConvert)
        
{
            
string text = null;
            
if (objectToConvert != null)
            
{
                XmlSerializer serializer 
= new XmlSerializer(objectToConvert.GetType());
                
using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                
{
                    serializer.Serialize((TextWriter)writer, objectToConvert);
                    text 
= writer.ToString();
                    writer.Close();
                }

            }

            
return text;
        }


        
public static object LoadBinaryFile(string path)
        
{
            
if (!File.Exists(path))
            
{
                
return null;
            }

            
using (FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read))
            
{
                BinaryReader reader 
= new BinaryReader(input);
                
byte[] buffer = new byte[input.Length];
                reader.Read(buffer, 
0, (int)input.Length);
                
return ConvertToObject(buffer);
            }

        }


        
public static bool SaveAsBinary(object objectToSave, string path)
        
{
            
if ((objectToSave != null&& CanBinarySerialize)
            
{
                
byte[] buffer = ConvertToBytes(objectToSave);
                
if (buffer != null)
                
{
                    
using (FileStream output = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                    
{
                        
using (BinaryWriter writer = new BinaryWriter(output))
                        
{
                            writer.Write(buffer);
                            
return true;
                        }

                    }

                }

            }

            
return false;
        }


        
public static void SaveAsXML(object objectToConvert, string path)
        
{
            
if (objectToConvert != null)
            
{
                XmlSerializer serializer 
= new XmlSerializer(objectToConvert.GetType());
                
using (StreamWriter writer = new StreamWriter(path))
                
{
                    serializer.Serialize((TextWriter)writer, objectToConvert);
                    writer.Close();
                }

            }

        }


        
public static string XMLDecode(string sTmp)
        
{
            
int[] numArray = new int[] 0x26600x3e0x220x3d0x27 };
            
for (int i = 0; i < numArray.Length; i++)
            
{
                sTmp 
= sTmp.Replace("&#" + numArray[i].ToString() + ";", ((char)numArray[i]).ToString());
            }

            
return sTmp;
        }


        
public static string XMLEncode(string sTmp)
        
{
            
int[] numArray = new int[] 0x26600x3e0x220x3d0x27 };
            
for (int i = 0; i < numArray.Length; i++)
            
{
                sTmp 
= sTmp.Replace(((char)numArray[i]).ToString(), "&#" + numArray[i].ToString() + ";");
            }

            
return sTmp;
        }

    }

}

posted on 2007-04-30 20:53  黄尚  阅读(582)  评论(2编辑  收藏  举报