using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;
class MainClass
{
private static void BinarySerialize(ArrayList list)
{
using (FileStream str = File.Create("people.bin"))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(str, list);
}
}
private static ArrayList BinaryDeserialize()
{
ArrayList people = null;
using (FileStream str = File.OpenRead("people.bin"))
{
BinaryFormatter bf = new BinaryFormatter();
people = (ArrayList)bf.Deserialize(str);
}
return people;
}
private static void SoapSerialize(ArrayList list)
{
using (FileStream str = File.Create("people.soap"))
{
SoapFormatter sf = new SoapFormatter();
sf.Serialize(str, list);
}
}
private static ArrayList SoapDeserialize()
{
ArrayList people = null;
using (FileStream str = File.OpenRead("people.soap"))
{
SoapFormatter sf = new SoapFormatter();
people = (ArrayList)sf.Deserialize(str);
}
return people;
}
public static void Main()
{
ArrayList people = new ArrayList();
people.Add("G");
people.Add("L");
people.Add("A");
BinarySerialize(people);
SoapSerialize(people);
ArrayList binaryPeople = BinaryDeserialize();
ArrayList soapPeople = SoapDeserialize();
Console.WriteLine("Binary people:");
foreach (string s in binaryPeople)
{
Console.WriteLine(" " + s);
}
Console.WriteLine("
SOAP people:");
foreach (string s in soapPeople)
{
Console.WriteLine(" " + s);
}
}
}
Month: February 2011
Serialize Class to Soap message
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
public class Serializer {
public static void Main(string [] args) {
StudentList personnel = CreateStudentList();
IFormatter soapFormatter = new SoapFormatter();
using (FileStream stream = File.OpenWrite("StudentListSoap.xml")) {
soapFormatter.Serialize(stream,personnel);
}
}
private static StudentList CreateStudentList() {
StudentList personnel = new StudentList();
personnel.Students = new Employee [] {new Employee()};
personnel.Students[0].FirstName = "Apple";
personnel.Students[0].MiddleInitial = "M";
personnel.Students[0].LastName = "Bear";
personnel.Students[0].Addresses = new Address [] {new Address()};
personnel.Students[0].Addresses[0].AddressType = AddressType.Home;
personnel.Students[0].Addresses[0].Street = new string [] {"Culloden"};
personnel.Students[0].Addresses[0].City = "Vancouver";
personnel.Students[0].Addresses[0].State = State.BC;
personnel.Students[0].Addresses[0].Zip = "V5V 4X7";
personnel.Students[0].StartDate = new DateTime(2006,10,12);
return personnel;
}
}
[Serializable]
public enum AddressType {
Home,
Office
}
[Serializable]
public enum State {
BC, ON
}
[Serializable]
public class Address {
public AddressType AddressType;
public string[] Street;
public string City;
public State State;
public string Zip;
}
[Serializable]
public class TelephoneNumber {
public string AreaCode;
public string Exchange;
public string Number;
}
[Serializable]
public class Employee {
public string FirstName;
public string MiddleInitial;
public string LastName;
public Address [] Addresses;
public TelephoneNumber [] TelephoneNumbers;
public DateTime StartDate;
}
[Serializable]
public class StudentList {
public Employee [] Students;
}
Serialize to SOAP based XML file
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
public class RoomApp
{
public static void Main()
{
// Make a room and listen to the tunes.
Console.WriteLine("Made a My Room...");
MyRoom myAuto = new MyRoom("My", 50, false, true);
myAuto.TurnOnRadio(true);
myAuto.GoUnderWater();
// Save the same room into SOAP format.
Console.WriteLine("Now saving room to XML file");
FileStream myStream = File.Create("RoomData.xml");
SoapFormatter myXMLFormat = new SoapFormatter();
myXMLFormat.Serialize(myStream, myAuto);
myStream.Close();
// Read in the Room from the XML file.
Console.WriteLine("Reading room from XML file.");
myStream = File.OpenRead("RoomData.xml");
MyRoom roomFromXML = (MyRoom)myXMLFormat.Deserialize(myStream);
Console.WriteLine(roomFromXML.PetName + " is alive!");
roomFromXML.TurnOnRadio(true);
myStream.Close();
}
}
[Serializable]
public class Radio
{
[NonSerialized]
private int objectIDNumber = 9;
public Radio(){}
public void On(bool state)
{
if(state == true)
Console.WriteLine("Music is on...");
else
Console.WriteLine("No tunes...");
}
}
[Serializable]
public class Room
{
protected string petName;
protected int maxInternetSpeed;
protected Radio theRadio = new Radio();
public Room(string petName, int maxInternetSpeed)
{
this.petName = petName;
this.maxInternetSpeed = maxInternetSpeed;
}
public Room() {}
public String PetName
{
get { return petName; }
set { petName = value; }
}
public int MaxInternetSpeed
{
get { return maxInternetSpeed; }
set { maxInternetSpeed = value; }
}
public void TurnOnRadio(bool state)
{
theRadio.On(state);
}
}
[Serializable]
public class MyRoom : Room
{
protected bool isFlightWorthy;
protected bool isSeaWorthy;
public MyRoom(string petName, int maxInternetSpeed,
bool canFly, bool canSubmerge)
: base(petName, maxInternetSpeed)
{
this.isFlightWorthy = canFly;
this.isSeaWorthy = canSubmerge;
}
public MyRoom(){}
public void Fly()
{
if(isFlightWorthy)
Console.WriteLine("Taking off!");
else
Console.WriteLine("Falling off cliff!");
}
public void GoUnderWater()
{
if(isSeaWorthy)
Console.WriteLine("Diving....");
else
Console.WriteLine("Drowning!!!");
}
}
Illustrates random access to a file
using System;
using System.IO;
public class RandomAccess {
public static void Main(String[] args) {
FileStream fileStream = new FileStream("test.cs", FileMode.Open);
fileStream.Seek(20, SeekOrigin.Begin);
byte[] anInt = new byte[4];
fileStream.Read(anInt,0,4);
int number = anInt[3];
for(int i = 2; i >= 0; i--){
number *= 256;
number += anInt[i];
}
Console.WriteLine("The number starting at byte 20 is {0}", number);
fileStream.Close();
}
}
Get Application Relative Path
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace WOSI.Utilities
{
public class FileUtils
{
public static string GetApplicationRelativePath(string relativePathFromAssembly)
{
return Path.GetFullPath(Path.GetDirectoryName(Application.ExecutablePath) + relativePathFromAssembly);
}
}
}
Combines two path strings.
#region License and Copyright
/* -------------------------------------------------------------------------
* Dotnet Commons IO
*
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
*
* Free Software Foundation, Inc.,
* 59 Temple Place,
* Suite 330,
* Boston,
* MA 02111-1307
* USA
*
* -------------------------------------------------------------------------
*/
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
namespace Dotnet.Commons.IO
{
class MainClass
{
/// ---------------------------------------------------------------
/// <summary>
/// Combines two path strings.
/// </summary>
/// <param name="path1">The first path.</param>
/// <param name="path2">The second path.</param>
/// <returns>
/// A string containing the combined paths. If one of the specified
/// paths is a zero-length string, this method returns the other path.
/// If <paramref name="path2" /> contains an absolute path, this method
/// returns <paramref name="path2" />.
/// </returns>
/// <remarks>
/// <para>
/// On Unix, processing is delegated to <see cref="Path.Combine(string, string)" />.
/// </para>
/// <para>
/// On Windows, this method normalized the paths to avoid running into
/// the 260 character limit of a path and converts forward slashes in
/// both <paramref name="path1" /> and <paramref name="path2" /> to
/// the platform's directory separator character.
/// </para>
///
/// Courtesy of NAnt project.
/// </remarks>
/// ---------------------------------------------------------------
public static string CombinePaths(string path1, string path2)
{
if (path1 == null)
{
throw new ArgumentNullException("path1");
}
if (path2 == null)
{
throw new ArgumentNullException("path2");
}
if (Path.IsPathRooted(path2))
{
return path2;
}
char separatorChar = Path.DirectorySeparatorChar;
char[] splitChars = new char[] { '/', separatorChar };
// Now we split the Path by the Path Separator
String[] path2Parts = path2.Split(splitChars);
ArrayList arList = new ArrayList();
// for each Item in the path that differs from ".." we just add it
// to the ArrayList, but skip empty parts
for (int iCount = 0; iCount < path2Parts.Length; iCount++)
{
string currentPart = path2Parts[iCount];
// skip empty parts or single dot parts
if (currentPart.Length == 0 || currentPart == ".")
{
continue;
}
// if we get a ".." Try to remove the last item added (as if
// going up in the Directory Structure)
if (currentPart == "..")
{
if (arList.Count > 0 && ((string)arList[arList.Count - 1] != ".."))
{
arList.RemoveAt(arList.Count - 1);
}
else
{
arList.Add(currentPart);
}
}
else
{
arList.Add(currentPart);
}
}
bool trailingSeparator = (path1.Length > 0 && path1.IndexOfAny(splitChars, path1.Length - 1) != -1);
// if the first path ends in directory seperator character, then
// we need to omit that trailing seperator when we split the path
string[] path1Parts;
if (trailingSeparator)
{
path1Parts = path1.Substring(0, path1.Length - 1).Split(splitChars);
}
else
{
path1Parts = path1.Split(splitChars);
}
int counter = path1Parts.Length;
// if the second path starts with parts to move up the directory tree,
// then remove corresponding parts in the first path
//
// eg. path1 = d:whateveryouwant odo
// path2 = ../../test
//
// ->
//
// path1 = d:whateveryouwant
// path2 = test
ArrayList arList2 = (ArrayList)arList.Clone();
for (int i = 0; i < arList2.Count; i++)
{
// never discard first part of path1
if ((string)arList2[i] != ".." || counter < 2)
{
break;
}
// skip part of current directory
counter--;
arList.RemoveAt(0);
}
string separatorString = separatorChar.ToString(CultureInfo.InvariantCulture);
// if path1 only has one remaining part, and the original path had
// a trailing separator character or the remaining path had multiple
// parts (which were discarded by a relative path in path2), then
// add separator to remaining part
if (counter == 1 && (trailingSeparator || path1Parts.Length > 1))
{
path1Parts[0] += separatorString;
}
string combinedPath = Path.Combine(string.Join(separatorString, path1Parts,
0, counter), string.Join(separatorString, (String[])arList.ToArray(typeof(String))));
// if path2 ends in directory separator character, then make sure
// combined path has trailing directory separator character
if (path2.EndsWith("/") || path2.EndsWith(separatorString))
{
combinedPath += Path.DirectorySeparatorChar;
}
return combinedPath;
}
}
}
Split the path into array of string
#region License and Copyright
/* -------------------------------------------------------------------------
* Dotnet Commons IO
*
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
*
* Free Software Foundation, Inc.,
* 59 Temple Place,
* Suite 330,
* Boston,
* MA 02111-1307
* USA
*
* -------------------------------------------------------------------------
*/
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
namespace Dotnet.Commons.IO
{
///
/// <summary>
/// This class provides basic facilities for manipulating files and file paths.
///
/// <h3>File-related methods</h3>
/// There are methods to
/// <list type="bullet">
/// <item>copy a file to another file,</item>
/// <item>compare the content of 2 files,</item>
/// <item>delete files using the wildcard character,</item>
/// <item>etc</item>
/// </list>
/// </summary>
///
public sealed class FileUtils
{
/// ---------------------------------------------------------------
/// <summary>
/// Determine if a path provided is the path of a file
/// </summary>
/// <param name="path"></param>
/// <returns>true if path is a valid file, false otherwise</returns>
/// ---------------------------------------------------------------
public static bool IsFile(string path)
{
return File.Exists(path);
}
/// ---------------------------------------------------------------
/// <summary>
/// Determine if a path is the path of a directory.
/// </summary>
/// <param name="path"></param>
/// <returns>true if path is a valid directory, false otherwise</returns>
/// ---------------------------------------------------------------
public static bool IsDirectory(string path)
{
return Directory.Exists(path);
}
/// ---------------------------------------------------------------
/// <summary>
/// Split the path into array of string
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
/// ---------------------------------------------------------------
public static String[] SplitPath(string path)
{
String[] pathSeparators = new String[] { "" };
return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries);
}
}
}

