Address Geocoding with C#

Sure an address class is simple, create a few properties for city, state, zip code, and away you go. Wouldn’t it be nice to also have your address automatically be able to geocode itself for automatic googlemapping at a later date? This article describes just how this is accomplished using c#.

Getting Started

Get yourself an API Key by going to: http://code.google.com/apis/maps/signup.html.

This article will use a bit of xml to parse the results that google will send out, so it might be good, if you have not used xml before to check out the MSDN Documentation

Let’s check out the namespaces we will be using:

//For getting our settings from our app.config or web.config file
using System.Configuration;

//For the streamreader object we will be using to get our results from the goog.
using System.IO;

//For reading the results that the Goog returns.
using System.Xml;

//For our webclient to contact Google.
System.Net;

You will need to add a reference to System.Configuration into your project so that the System.ConfigurationManager object will have the AppSettings object attached to it.

Once we have our imports all squared away we will need to get our class and basic properties all setup.

public class Address
{
	//These are abbreviated property declarations as we do not need the private
	//variables for these simple properties.
	public string Latitude { get; set; }
	public string Longitude { get; set; }
	public string Line1 { get; set; }
	public string Line2 { get; set; }
	public string City { get; set; }
	public string State { get; set; }
	public string Zip { get; set; }
	public string Country { get; set; }

	//whereas this property is a read only and, therefore, we need some way to
	//set our property from inside the class without someone outside the object
	//being able to overwrite.
	private LatLngAccurateToTypes _LatLngAccuracy = 0;
	public LatLngAccurateToTypes LatLngAccuracy
	{
		get { return _LatLngAccuracy; }
	}

Quick Tip: The prop snippet.

I love snippets; I use them all the time. If you type in “prop” and hit the tab key twice, a nicely formatted property will appear before you for your quick entry.

Add Some Flavor

To make our address class a bit more functional, we are going override our ToString method to give us a nicely formatted address string.

	public override string ToString()
	{
		//Using the stringbuilder gives us better performance than stinky concatenation.
		System.Text.StringBuilder sb = new System.Text.StringBuilder();

		//Assume we have a line 1
		sb.AppendLine(Line1);

		//now check if the string is null or empty before appending
		if (!string.IsNullOrEmpty(Line2)) sb.AppendLine(Line2);

		//one could expand upon this to check for values in the other properties.
		sb.Append(City);
		sb.Append(", ");
		sb.Append(State);
		sb.Append(" ");
		sb.Append(Zip);
		sb.Append(" ");
		sb.Append(Country);

		//send out our new string
		return sb.ToString();
	}

Ok, Let’s GeoCode

Even though we can assume that Google already knows what we are about to send them, we can still assume that they would like to be asked, so we will now send our data to Google for GeoCoding.

	public void GeoCode()
	{
		//Setup a streamreader for retrieving data from Google.
		//This is line that requires System.IO.
		StreamReader sr = null;

		//Get the maps key in the web config file.
		//This is what we needed the reference to System.Configuration for.
		string mapskey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"];

		//Check to see if our maps key exists
		if (string.IsNullOrEmpty(mapskey))
		{
			//if the key does not exist, we have an error so throw an exception.
			throw new Exception("No valid google maps api key to use for geocoding.  Please add an app key named \"GoogleMapsAPIKey\" to the web.config file.");
		}

		//Create the url string to send our request to googsie.
		string url = string.Format("http://maps.google.com/maps/geo?q={0} +{1} +{2} +{3} +{4}&output=xml&oe=utf8&sensor=false&key={5}", this.Line1, this.City + ", ", this.State, this.Zip, this.Country, mapskey);

		//Create a web request client.
		//This is where the System.Net import is used.
		WebClient wc = new WebClient();

		//Even though logic would tell us that having a site outage is a bit evil and Google is never evil,
		//therefore Google will never have a site outage, we will still throw a try catch around our call
		//just in case Google does become evil for a few minutes on some random day.
		try
		{
			//retrieve our result and put it in a streamreader
			sr = new StreamReader(wc.OpenRead(url));
		}
		catch (Exception ex)
		{
			//This is where we can assume they were evil.
			throw new Exception("An error occured while retrieving GeoCoded results from Google, the error was: " + ex.Message);
		}

		try
		{
			//Now that we have the results, lets parse the returned data with an xmltextreader.
			//Why an XMLTextReader vs. An XMLDocument?  Simple, XMLTextReaders are faster and this is
			//Simple enough not to warrant a full XMLDocument.
			XmlTextReader xtr = new XmlTextReader(sr);

			bool coordread = false;
			bool accread = false;

			//Start reading our xml document.
			while (xtr.Read())
			{
				xtr.MoveToElement();
				switch (xtr.Name)
				{
					case "AddressDetails": //Check for the address details node
						while (xtr.MoveToNextAttribute())
						{
							switch (xtr.Name)
							{
								case "Accuracy": //move into the accuracy attrib and....
									if (!accread)
									{
										//get the accuracy, convert it to our enum and save it to the record
										this._LatLngAccuracy = (LatLngAccurateToTypes)Convert.ToInt32(xtr.Value);
										accread = true;
									}
									break;
							}
						}
						break;
					case "coordinates": //the coordinates element
						if (!coordread)
						{
							//move into the element value
							xtr.Read();

							//split the coords and then..
							string[] coords = xtr.Value.Split(new char[] { ',' });

							//save the values
							Longitude = coords[0];
							Latitude = coords[1];

							//finally, once this has been done, we don't want the process to run again on the same file
							coordread = true;
						}
						break;
				}
			}
		}
		catch (Exception ex)
		{
			throw new Exception("An error occured while parsing GeoCoded results from Google, the error was: " + ex.Message);
		}
	}

Ok, so there we go, we have now GeoCoded our address for saving into our database or throwing onto a dynamic Google map. There is only one thing we are missing. Google returns an enum of accuracy types for their results. If our address only contains a city, the GeoCode will be far less accurate than if we were to put in a full address. The enum below helps us to track that.

	public enum LatLngAccurateToTypes : int
	{
		Unknown = 0,
		Country = 1,
		Region = 2,
		SubRegion = 3,
		Town = 4,
		PostCode = 5,
		Street = 6,
		Intersection = 7,
		Address = 8,
		Premises = 9
	}

Full Source

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using System.Net;
using System.Web;
using System.Configuration;
using System.IO;
using System.Xml;

public class Address
{
	public string Latitude { get; set; }
	public string Longitude { get; set; }
	public string Line1 { get; set; }
	public string Line2 { get; set; }
	public string City { get; set; }
	public string State { get; set; }
	public string Zip { get; set; }
	public string Country { get; set; }

	private LatLngAccurateToTypes _LatLngAccuracy = 0;
	public LatLngAccurateToTypes LatLngAccuracy
	{
		get { return _LatLngAccuracy; }
	}

	public override string ToString()
	{
		System.Text.StringBuilder sb = new System.Text.StringBuilder();
		sb.AppendLine(Line1);
		if (!string.IsNullOrEmpty(Line2)) sb.AppendLine(Line2);
		sb.Append(City);
		sb.Append(", ");
		sb.Append(State);
		sb.Append(" ");
		sb.Append(Zip);
		sb.Append(" ");
		sb.Append(Country);
		return sb.ToString();
	}

	public Address()
	{
	}

	public void GeoCode()
	{
		//get the maps key in the web config file
		string mapskey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"];
		//setup a streamreader for retrieving data from Google.
		StreamReader sr = null;

		//Check to see if our maps key exists
		if (string.IsNullOrEmpty(mapskey))
		{
			throw new Exception("No valid google maps api key to use for geocoding.  Please add an app key named \"GoogleMapsAPIKey\" to the web.config file.");
		}

		//Create the url string to send our request to googs.
		string url = string.Format("http://maps.google.com/maps/geo?q={0} +{1} +{2} +{3} +{4}&output=xml&oe=utf8&sensor=false&key={5}", this.Line1, this.City + ", ", this.State, this.Zip, this.Country, mapskey);

		//Create a web request client.
		WebClient wc = new WebClient();

		try
		{
			//retrieve our result and put it in a streamreader
			sr = new StreamReader(wc.OpenRead(url));
		}
		catch (Exception ex)
		{
			throw new Exception("An error occured while retrieving GeoCoded results from Google, the error was: " + ex.Message);
		}

		try
		{
			//now lets parse the returned data as an xml
			XmlTextReader xtr = new XmlTextReader(sr);
			bool coordread = false;
			bool accread = false;
			while (xtr.Read())
			{
				xtr.MoveToElement();
				switch (xtr.Name)
				{
					case "AddressDetails": //Check for the address details node
						while (xtr.MoveToNextAttribute())
						{
							switch (xtr.Name)
							{
								case "Accuracy": //move into the accuracy attrib and....
									if (!accread)
									{
										//get the accuracy, convert it to our enum and save it to the record
										this._LatLngAccuracy = (LatLngAccurateToTypes)Convert.ToInt32(xtr.Value);
										accread = true;
									}
									break;
							}
						}
						break;
					case "coordinates": //the coordinates element
						if (!coordread)
						{
							//move into the element value
							xtr.Read();

							//split the coords and then..
							string[] coords = xtr.Value.Split(new char[] { ',' });

							//save the values
							Longitude = coords[0];
							Latitude = coords[1];

							//finally, once this has been done, we don't want the process to run again on the same file
							coordread = true;
						}
						break;
				}
			}
		}
		catch (Exception ex)
		{
			throw new Exception("An error occured while parsing GeoCoded results from Google, the error was: " + ex.Message);
		}
	}

	public enum LatLngAccurateToTypes : int
	{
		Unknown = 0,
		Country = 1,
		Region = 2,
		SubRegion = 3,
		Town = 4,
		PostCode = 5,
		Street = 6,
		Intersection = 7,
		Address = 8,
		Premises = 9
	}
}
Advertisements

A Simple c# Wrapper for ffMpeg

Converting video in .Net is a pain in the butt. The .Net framework, as of 2/8/2010 does not have a nice, simple, conversion process that will take a file in the many different formats out there and drop it into a nicely formatted .flv file for easy slideshowpro (or other flash based package) streaming.

The alternative, that I have most often seen, is using ffMpeg to convert source video into .flv format. Unfortunately, this process can a bit arcane. While there are other libraries out there that wrap up ffMpeg with a nice shiny, albeit complex, bow. I figured there might be some use for a simple c# library that does a couple simple, but very useful processes.

The following class will convert your input file to a .flv file and create a preview image from 1/3 of the way into the movie. By getting the preview image from 1/3 into the movie, we can avoid a completely black preview image that can come from a video that fades in.

Getting Started:

Create a directory in your project that contains the ffMpeg.exe file, this file will be referenced by the class below. This class is also going to use the web.config or app.config to store the location of our ffMpeg.exe file and a couple key settings. To do this, you will need to import system.configuration into your project and include the following line:

	using System.Configuration;

To start with, we have a couple properties that expose the working path that ffMpeg will need while it is processing our video file along with a property that exposes the location of our exe file.

	private string _ffExe;
	public string ffExe
	{
		get
		{
			return _ffExe;
		}
		set
		{
			_ffExe = value;
		}
	}

	private string _WorkingPath;
	public string WorkingPath
	{
		get
		{
			return _WorkingPath;
		}
		set
		{
			_WorkingPath = value;
		}
	}

In our constructors, we will call an initialize method that will attempt to grab our exepath from web.config, assuming that one has not been entered into our second constructor.

Note: In this example, the class is name “Converter”

	public Converter()
	{
		Initialize();
	}
	public Converter(string ffmpegExePath)
	{
		_ffExe = ffmpegExePath;
		Initialize();
	}

Initialization

You will note that the we are testing to see if the ffmpeg.exe file location exists before attempting to pull it from web.config.

	//Make sure we have valid ffMpeg.exe file and working directory to do our dirty work.
	private void Initialize()
	{
		//first make sure we have a value for the ffexe file setting
		if (string.IsNullOrEmpty(_ffExe))
		{
			object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];
			if (o == null)
			{
				throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +
				"can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +
				"in the appsettings section, the correct property name is: ffmpeg:ExeLocation");
			}
			else
			{
				if (string.IsNullOrEmpty(o.ToString()))
				{
					throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");
				}
				_ffExe = o.ToString();
			}
		}

		//Now see if ffmpeg.exe exists
		string workingpath = GetWorkingFile();
		if (string.IsNullOrEmpty(workingpath))
		{
			//ffmpeg doesn't exist at the location stated.
			throw new Exception("Could not find a copy of ffmpeg.exe");
		}
		_ffExe = workingpath;

		//now see if we have a temporary place to work
		if (string.IsNullOrEmpty(_WorkingPath))
		{
			object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];
			if (o != null)
			{
				_WorkingPath = o.ToString();
			}
			else
			{
				_WorkingPath = string.Empty;
			}
		}
	}

	private string GetWorkingFile()
	{
		//try the stated directory
		if (File.Exists(_ffExe))
		{
			return _ffExe;
		}

		//oops, that didn't work, try the base directory
		if (File.Exists(Path.GetFileName(_ffExe)))
		{
			return Path.GetFileName(_ffExe);
		}

		//well, now we are really unlucky, let's just return null
		return null;
	}

Loading Files Without Creating Locks

These subs might be a bit out of place but are useful as they create our memory resident objects without throwing a lock on the source file. This means that we can run more than one process at once, or delete our file without screwing things up for another process.

	public static System.Drawing.Image LoadImageFromFile(string fileName)
	{
		System.Drawing.Image theImage = null;
		using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
		FileAccess.Read))
		{
			byte[] img;
			img = new byte[fileStream.Length];
			fileStream.Read(img, 0, img.Length);
			fileStream.Close();
			theImage = System.Drawing.Image.FromStream(new MemoryStream(img));
			img = null;
		}
		GC.Collect();
		return theImage;
	}

	public static MemoryStream LoadMemoryStreamFromFile(string fileName)
	{
		MemoryStream ms = null;
		using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
		FileAccess.Read))
		{
			byte[] fil;
			fil = new byte[fileStream.Length];
			fileStream.Read(fil, 0, fil.Length);
			fileStream.Close();
			ms = new MemoryStream(fil);
		}
		GC.Collect();
		return ms;
	}

Running the ffMpeg Process

Now that we have setup our class and have some basic helper subs to get us going, we need to actually have a method that will run the ffMpeg process.


	//Note the private call here and the argument for Parameters.  The private call is
	//being made here because, in this class, we don't really want to have this method
	//called from outside of the class -- this, however flies in the face of allowing the
	//parameters argument (why not just allow out the public call so that a developer can
	//put in the parameters from their own code?  I guess one could do it and it would probably
	//work fine but, for this implementation, I chose to leave it private.
	private string RunProcess(string Parameters)
	{
		//create a process info object so we can run our app
		ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
		oInfo.UseShellExecute = false;
		oInfo.CreateNoWindow = true;

		//so we are going to redirect the output and error so that we can parse the return
		oInfo.RedirectStandardOutput = true;
		oInfo.RedirectStandardError = true;

		//Create the output and streamreader to get the output
		string output = null; StreamReader srOutput = null;

		//try the process
		try
		{
			//run the process
			Process proc = System.Diagnostics.Process.Start(oInfo);

			proc.WaitForExit();

			//get the output
			srOutput = proc.StandardError;

			//now put it in a string
			output = srOutput.ReadToEnd();

			proc.Close();
		}
		catch (Exception)
		{
			output = string.Empty;
		}
		finally
		{
			//now, if we succeded, close out the streamreader
			if (srOutput != null)
			{
				srOutput.Close();
				srOutput.Dispose();
			}
		}
		return output;
	}

Now let’s make some functional stuff

Now that we have called the ffMpeg process, we need to get some video info, get a video file, and a preview image. So, with that being said, onto more source code.

Getting the Details

So, we need to now parse the details of our ffMpeg.exe output and read some details about the video file.

	//We are going to take in memory stream for this file to allow for different input options.
	//Unfortunately, this means that we also need the file extension to pass it out to ffMpeg.
	public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename)
	{
		//Create a temporary file for our use in ffMpeg
		string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
		FileStream fs = File.Create(tempfile);

		//write the memory stream to a file and close our the stream so it can be used again.
		inputFile.WriteTo(fs);
		fs.Flush();
		fs.Close();
		GC.Collect();

		//Video File is a class you will see further down this post.  It has some basic information about the video
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(tempfile);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		//And, without adieu, a call to our main method for this functionality.
		GetVideoInfo(vf);

		try
		{
			File.Delete(tempfile);
		}
		catch (Exception)
		{

		}

		return vf;
	}

	//This sub is just another overload to allow input of a direct path, we are just
	//using the videofile class to send in.  More on the video file class further down
	//the article.
	public VideoFile GetVideoInfo(string inputPath)
	{
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(inputPath);
		}
		catch (Exception ex)
		{
			throw ex;
		}
		GetVideoInfo(vf);
		return vf;
	}

	//And now the important code for the GetVideoInfo
	public void GetVideoInfo(VideoFile input)
	{
		//set up the parameters for video info -- these will be passed into ffMpeg.exe
		string Params = string.Format("-i {0}", input.Path);
		string output = RunProcess(Params);
		input.RawInfo = output;

		//Use a regular expression to get the different properties from the video parsed out.
		Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
		Match m = re.Match(input.RawInfo);

		if (m.Success)
		{
			string duration = m.Groups[1].Value;
			string[] timepieces = duration.Split(new char[] { ':', '.' });
			if (timepieces.Length == 4)
			{
				input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
			}
		}

		//get audio bit rate
		re = new Regex("[B|b]itrate:.((\\d|:)*)");
		m = re.Match(input.RawInfo);
		double kb = 0.0;
		if (m.Success)
		{
			Double.TryParse(m.Groups[1].Value, out kb);
		}
		input.BitRate = kb;

		//get the audio format
		re = new Regex("[A|a]udio:.*");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			input.AudioFormat = m.Value;
		}

		//get the video format
		re = new Regex("[V|v]ideo:.*");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			input.VideoFormat = m.Value;
		}

		//get the video format
		re = new Regex("(\\d{2,3})x(\\d{2,3})");
		m = re.Match(input.RawInfo);
		if (m.Success)
		{
			int width = 0; int height = 0;
			int.TryParse(m.Groups[1].Value, out width);
			int.TryParse(m.Groups[2].Value, out height);
			input.Width = width;
			input.Height = height;
		}
		input.infoGathered = true;
	}

Finally, do the conversion

So, here is the conversion meat and preview imaging.

	//Note the ouputpackage object output.  The output package class is detailed below.
	//this overload does much the same as the one above does, in that, it offers the ability
	//to input a memory stream vs. a filename or our videofile input class.
	public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename)
	{
		string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
		FileStream fs = File.Create(tempfile);
		inputFile.WriteTo(fs);
		fs.Flush();
		fs.Close();
		GC.Collect();

		VideoFile vf = null;
		try
		{
			vf = new VideoFile(tempfile);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		OutputPackage oo = ConvertToFLV(vf);

		try{
			File.Delete(tempfile);
		} catch(Exception) {

		}

		return oo;
	}
	public OutputPackage ConvertToFLV(string inputPath)
	{
		VideoFile vf = null;
		try
		{
			vf = new VideoFile(inputPath);
		}
		catch (Exception ex)
		{
			throw ex;
		}

		OutputPackage oo = ConvertToFLV(vf);
		return oo;
	}

	//The actually important code, rather than an overload.
	public OutputPackage ConvertToFLV(VideoFile input)
	{
		//check to see if we have already gathered our info so we know
		//where to get our preview image from.
		if (!input.infoGathered)
		{
			GetVideoInfo(input);
		}

		//Create our output object
		OutputPackage ou = new OutputPackage();

		//set up the parameters for getting a previewimage
		string filename = System.Guid.NewGuid().ToString() + ".jpg";
		int secs;

		//divide the duration in 3 to get a preview image in the middle of the clip
		//instead of a black image from the beginning.
		secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);

		string finalpath = Path.Combine(this.WorkingPath, filename);

		//These are the parameters for setting up a preview image that must be passed to ffmpeg.
		//Note that we are asking for a jpeg image at our specified seconds.
		string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);
		string output = RunProcess(Params);

		ou.RawOutput = output;

		//Ok, so hopefully we now have a preview file.  If the file
		//did not get created properly, try again at the first frame.
		if (File.Exists(finalpath))
		{
			//load that file into our output package and attempt to delete the file
			//since we no longer need it.
			ou.PreviewImage = LoadImageFromFile(finalpath);
			try
			{
				File.Delete(finalpath);
			}
			catch (Exception) { }
		} else { //try running again at frame 1 to get something
			Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);
			output = RunProcess(Params);

			ou.RawOutput = output;

			if (File.Exists(finalpath)) {
				ou.PreviewImage = LoadImageFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			}
		}

		finalpath = Path.Combine(this.WorkingPath, filename);
		filename = System.Guid.NewGuid().ToString() + ".flv";

		//Now we are going to actually create the converted file.  Note that we are asking for
		//a video at 22khz 64bit.  This can be changed by a couple quick alterations to this line,
		//or by extending out this class to offer multiple different conversions.
		Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);
		output = RunProcess(Params);

		//Check to see if our conversion file exists and then load the converted
		//file into our output package.  If the file does exist and we are able to
		//load it into our output package, we can delete the work file.
		if (File.Exists(finalpath))
		{
			ou.VideoStream = LoadMemoryStreamFromFile(finalpath);
			try
			{
				File.Delete(finalpath);
			}
			catch (Exception) { }
		}
		return ou;
	}

Supplementary Classes

Throughout this article, you will have noticed the use of “VideoFile” and “OutputPackage”. These classes are just informational classes that provide simple ways of accessing everything.
Here they are:

	public class VideoFile
	{
		#region Properties
		private string _Path;
		public string Path
		{
			get
			{
				return _Path;
			}
			set
			{
				_Path = value;
			}
		}

		public TimeSpan Duration { get; set; }
		public double BitRate { get; set; }
		public string AudioFormat { get; set; }
		public string VideoFormat { get; set; }
		public int Height { get; set; }
		public int Width { get; set; }
		public string RawInfo { get; set; }
		public bool infoGathered {get; set;}
		#endregion

		#region Constructors
		public VideoFile(string path)
		{
			_Path = path;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			this.infoGathered = false;
			//first make sure we have a value for the video file setting
			if (string.IsNullOrEmpty(_Path))
			{
				throw new Exception("Could not find the location of the video file");
			}

			//Now see if the video file exists
			if (!File.Exists(_Path))
			{
				throw new Exception("The video file " + _Path + " does not exist.");
			}
		}
		#endregion
	}

	public class OutputPackage
	{
		public MemoryStream VideoStream { get; set; }
		public System.Drawing.Image PreviewImage { get; set; }
		public string RawOutput { get; set; }
		public bool Success { get; set; }
	}

Full Code for the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Text.RegularExpressions;

namespace ffMpeg
{
	public class Converter
	{
		#region Properties
		private string _ffExe;
		public string ffExe
		{
			get
			{
				return _ffExe;
			}
			set
			{
				_ffExe = value;
			}
		}

		private string _WorkingPath;
		public string WorkingPath
		{
			get
			{
				return _WorkingPath;
			}
			set
			{
				_WorkingPath = value;
			}
		}

		#endregion

		#region Constructors
		public Converter()
		{
			Initialize();
		}
		public Converter(string ffmpegExePath)
		{
			_ffExe = ffmpegExePath;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			//first make sure we have a value for the ffexe file setting
			if (string.IsNullOrEmpty(_ffExe))
			{
				object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];
				if (o == null)
				{
					throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +
					"can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +
					"in the appsettings section, the correct property name is: ffmpeg:ExeLocation");
				}
				else
				{
					if (string.IsNullOrEmpty(o.ToString()))
					{
						throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");
					}
					_ffExe = o.ToString();
				}
			}

			//Now see if ffmpeg.exe exists
			string workingpath = GetWorkingFile();
			if (string.IsNullOrEmpty(workingpath))
			{
				//ffmpeg doesn't exist at the location stated.
				throw new Exception("Could not find a copy of ffmpeg.exe");
			}
			_ffExe = workingpath;

			//now see if we have a temporary place to work
			if (string.IsNullOrEmpty(_WorkingPath))
			{
				object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];
				if (o != null)
				{
					_WorkingPath = o.ToString();
				}
				else
				{
					_WorkingPath = string.Empty;
				}
			}
		}

		private string GetWorkingFile()
		{
			//try the stated directory
			if (File.Exists(_ffExe))
			{
				return _ffExe;
			}

			//oops, that didn't work, try the base directory
			if (File.Exists(Path.GetFileName(_ffExe)))
			{
				return Path.GetFileName(_ffExe);
			}

			//well, now we are really unlucky, let's just return null
			return null;
		}
		#endregion

		#region Get the File without creating a file lock
		public static System.Drawing.Image LoadImageFromFile(string fileName)
		{
			System.Drawing.Image theImage = null;
			using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
			FileAccess.Read))
			{
				byte[] img;
				img = new byte[fileStream.Length];
				fileStream.Read(img, 0, img.Length);
				fileStream.Close();
				theImage = System.Drawing.Image.FromStream(new MemoryStream(img));
				img = null;
			}
			GC.Collect();
			return theImage;
		}

		public static MemoryStream LoadMemoryStreamFromFile(string fileName)
		{
			MemoryStream ms = null;
			using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
			FileAccess.Read))
			{
				byte[] fil;
				fil = new byte[fileStream.Length];
				fileStream.Read(fil, 0, fil.Length);
				fileStream.Close();
				ms = new MemoryStream(fil);
			}
			GC.Collect();
			return ms;
		}
		#endregion

		#region Run the process
		private string RunProcess(string Parameters)
		{
			//create a process info
			ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
			oInfo.UseShellExecute = false;
			oInfo.CreateNoWindow = true;
			oInfo.RedirectStandardOutput = true;
			oInfo.RedirectStandardError = true;

			//Create the output and streamreader to get the output
			string output = null; StreamReader srOutput = null;

			//try the process
			try
			{
				//run the process
				Process proc = System.Diagnostics.Process.Start(oInfo);

				proc.WaitForExit();

				//get the output
				srOutput = proc.StandardError;

				//now put it in a string
				output = srOutput.ReadToEnd();

				proc.Close();
			}
			catch (Exception)
			{
				output = string.Empty;
			}
			finally
			{
				//now, if we succeded, close out the streamreader
				if (srOutput != null)
				{
					srOutput.Close();
					srOutput.Dispose();
				}
			}
			return output;
		}
		#endregion

		#region GetVideoInfo
		public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename)
		{
			string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
			FileStream fs = File.Create(tempfile);
			inputFile.WriteTo(fs);
			fs.Flush();
			fs.Close();
			GC.Collect();

			VideoFile vf = null;
			try
			{
				vf = new VideoFile(tempfile);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			GetVideoInfo(vf);

			try
			{
				File.Delete(tempfile);
			}
			catch (Exception)
			{

			}

			return vf;
		}
		public VideoFile GetVideoInfo(string inputPath)
		{
			VideoFile vf = null;
			try
			{
				vf = new VideoFile(inputPath);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			GetVideoInfo(vf);
			return vf;
		}
		public void GetVideoInfo(VideoFile input)
		{
			//set up the parameters for video info
			string Params = string.Format("-i {0}", input.Path);
			string output = RunProcess(Params);
			input.RawInfo = output;

			//get duration
			Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
			Match m = re.Match(input.RawInfo);

			if (m.Success)
			{
				string duration = m.Groups[1].Value;
				string[] timepieces = duration.Split(new char[] { ':', '.' });
				if (timepieces.Length == 4)
				{
					input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
				}
			}

			//get audio bit rate
			re = new Regex("[B|b]itrate:.((\\d|:)*)");
			m = re.Match(input.RawInfo);
			double kb = 0.0;
			if (m.Success)
			{
				Double.TryParse(m.Groups[1].Value, out kb);
			}
			input.BitRate = kb;

			//get the audio format
			re = new Regex("[A|a]udio:.*");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				input.AudioFormat = m.Value;
			}

			//get the video format
			re = new Regex("[V|v]ideo:.*");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				input.VideoFormat = m.Value;
			}

			//get the video format
			re = new Regex("(\\d{2,3})x(\\d{2,3})");
			m = re.Match(input.RawInfo);
			if (m.Success)
			{
				int width = 0; int height = 0;
				int.TryParse(m.Groups[1].Value, out width);
				int.TryParse(m.Groups[2].Value, out height);
				input.Width = width;
				input.Height = height;
			}
			input.infoGathered = true;
		}
		#endregion

		#region Convert to FLV
		public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename)
		{
			string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
			FileStream fs = File.Create(tempfile);
			inputFile.WriteTo(fs);
			fs.Flush();
			fs.Close();
			GC.Collect();

			VideoFile vf = null;
			try
			{
				vf = new VideoFile(tempfile);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			OutputPackage oo = ConvertToFLV(vf);

			try{
				File.Delete(tempfile);
			} catch(Exception) {

			}

			return oo;
		}
		public OutputPackage ConvertToFLV(string inputPath)
		{
			VideoFile vf = null;
			try
			{
				vf = new VideoFile(inputPath);
			}
			catch (Exception ex)
			{
				throw ex;
			}

			OutputPackage oo = ConvertToFLV(vf);
			return oo;
		}
		public OutputPackage ConvertToFLV(VideoFile input)
		{
			if (!input.infoGathered)
			{
				GetVideoInfo(input);
			}
			OutputPackage ou = new OutputPackage();

			//set up the parameters for getting a previewimage
			string filename = System.Guid.NewGuid().ToString() + ".jpg";
			int secs;

			//divide the duration in 3 to get a preview image in the middle of the clip
			//instead of a black image from the beginning.
			secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);

			string finalpath = Path.Combine(this.WorkingPath, filename);
			string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);
			string output = RunProcess(Params);

			ou.RawOutput = output;

			if (File.Exists(finalpath))
			{
				ou.PreviewImage = LoadImageFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			} else { //try running again at frame 1 to get something
				Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);
				output = RunProcess(Params);

				ou.RawOutput = output;

				if (File.Exists(finalpath)) {
					ou.PreviewImage = LoadImageFromFile(finalpath);
					try
					{
						File.Delete(finalpath);
					}
					catch (Exception) { }
				}
			}

			finalpath = Path.Combine(this.WorkingPath, filename);
			filename = System.Guid.NewGuid().ToString() + ".flv";
			Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);
			output = RunProcess(Params);

			if (File.Exists(finalpath))
			{
				ou.VideoStream = LoadMemoryStreamFromFile(finalpath);
				try
				{
					File.Delete(finalpath);
				}
				catch (Exception) { }
			}
			return ou;
		}
		#endregion
	}

	public class VideoFile
	{
		#region Properties
		private string _Path;
		public string Path
		{
			get
			{
				return _Path;
			}
			set
			{
				_Path = value;
			}
		}

		public TimeSpan Duration { get; set; }
		public double BitRate { get; set; }
		public string AudioFormat { get; set; }
		public string VideoFormat { get; set; }
		public int Height { get; set; }
		public int Width { get; set; }
		public string RawInfo { get; set; }
		public bool infoGathered {get; set;}
		#endregion

		#region Constructors
		public VideoFile(string path)
		{
			_Path = path;
			Initialize();
		}
		#endregion

		#region Initialization
		private void Initialize()
		{
			this.infoGathered = false;
			//first make sure we have a value for the video file setting
			if (string.IsNullOrEmpty(_Path))
			{
				throw new Exception("Could not find the location of the video file");
			}

			//Now see if the video file exists
			if (!File.Exists(_Path))
			{
				throw new Exception("The video file " + _Path + " does not exist.");
			}
		}
		#endregion
	}

	public class OutputPackage
	{
		public MemoryStream VideoStream { get; set; }
		public System.Drawing.Image PreviewImage { get; set; }
		public string RawOutput { get; set; }
		public bool Success { get; set; }
	}
}