Click here to Skip to main content
15,892,643 members
Articles / Programming Languages / C#

Console FTP in C#

Rate me:
Please Sign up or sign in to vote.
3.78/5 (17 votes)
7 Mar 20043 min read 224.7K   3K   46  
A basic FTP client in C#.
using System;
using System.Text;
using System.Collections;
using System.IO;

namespace HB.Web.Ftp
{
	public class WindowsFileNode: FileNode
	{
		/// <summary>
		/// Creates a new FTP file.
		/// </summary>
		/// <param name="name">The name of the file.</param>
		/// <param name="fullname">The full path of the file.</param>
		/// <param name="isDirectory">Indicates if the file is a directory.</param>
		/// <param name="lastWriteTime">The last time the file was written to.</param>
		/// <param name="length">The filesize.</param>
		/// <param name="ext">The file extension of the file.</param>
		/// <param name="dirName">The full path of the file's directory.</param>
		/// <exception cref="ArgumentNullException">When parameter name, fullname
		/// or dirName is null.</exception>
		public WindowsFileNode(string name, string fullname, bool isDirectory, string ext,
			DateTime lastWriteTime, long length, string dirName)
			: base(name, fullname, isDirectory, lastWriteTime, length, dirName, ext)
		{
		}

		public WindowsFileNode() : base()
		{
		}

		public WindowsFileNode(WindowsFileNode node) : base(node)
		{
		}

		static WindowsFileNode()
		{
			numFormat = new System.Globalization.NumberFormatInfo();
			numFormat.NumberDecimalDigits = 0;
		}

		/// <summary>
		/// parses the dir listing and determines the filesize, filename, creation date, etc.
		/// </summary>
		/// <returns>false if the listing wasn't in an acceptable format</returns>
		public override FileNode Parse(string text, string absolutePath)
		{
			try
			{
				//12-29-02  11:41PM <DIR> Apps
				//01-34-67--01-3456
				string month, day, year;
				string ext = "";
				string[] test = text.Split(Convert.ToChar(" "));
				if(test.Length < 6)
					throw new ApplicationException();
				string parse = text;
				month = parse.Substring(0, 2);
				day = parse.Substring(3, 2);
				year = parse.Substring(6, 2);
				string hour = parse.Substring(10, 2);
				string min = parse.Substring(13, 2);
				string tod = parse.Substring(15, 2);
				parse = parse.Substring(17);
				long size = 0;
				bool isDir = false;
				while(parse.StartsWith(" "))
					parse = parse.Substring(1);
				if(parse.StartsWith("<DIR>"))
				{
					isDir = true;
					size = 0;
					parse = parse.Substring(5);
					while(parse.StartsWith(" "))
						parse = parse.Substring(1);
				}
				else
				{
					isDir = false;
					size = long.Parse(parse.Split(char.Parse(" "))[0]);
					parse = parse.Substring(parse.Split(char.Parse(" "))[0].Length);
				}
				string filename = parse;
					
				if(year.StartsWith("0")) year = "20" + year;
				else year = "19" + year;
				int hr = int.Parse(hour);
				if(tod.ToUpper()== "PM")
					if(hr != 12) hr+=12;
					else
						if(hr == 12)
						hr = 0;
				DateTime dt = DateTime.Parse(month + " " + day + " " + year, new System.Globalization.CultureInfo("en-US"));
				dt = new DateTime(dt.Year, dt.Month, dt.Day, hr, int.Parse(min), 0);		
				//TODO: another unsure
				//if(fullPath == "/") fullPath = fullPath + filename;
				string path = absolutePath;
				if(path.EndsWith("/")) path = path + filename;
				else path = path + "/" + filename;
				return new WindowsFileNode(filename, path, isDir, ext, dt, size, absolutePath);
			}
			catch
			{
				throw new FormatException("A WindowsFileNode could not be created using the following text: " + text);
			}
		}

		public override FileNode[] FromFtpList(string list, string path)
		{
			StringReader reader = null;
			try
			{
				reader = new StringReader(list);
				ArrayList nodes = new ArrayList();
				string listing;
				while(reader.Peek() != -1)
				{
					listing = reader.ReadLine();
					nodes.Add(Parse(listing, path));
				}
				return (FileNode[]) nodes.ToArray(typeof(WindowsFileNode));
			}
			finally
			{
				try
				{
					reader.Close();
				}
				catch{}
			}
		}

		public override void Delete(DirectoryList list, System.IO.TextWriter clientOutput, System.IO.TextWriter serverOutput)
		{
			throw new NotImplementedException();
		}

		public override FileNode[] GetDirectories(DirectoryList list, System.IO.TextWriter clientOutput, System.IO.TextWriter serverOutput)
		{
			byte[] dirList = list.GetList(DirectoryName, clientOutput, serverOutput);
			ArrayList fileNodes = new ArrayList(FromFtpList(Encoding.ASCII.GetString(dirList), DirectoryName));
			for(int i = 0; i < fileNodes.Count; i++)
				if(((FileNode) fileNodes[i]).IsDirectory)
					fileNodes.RemoveAt(i--);
			return (FileNode[]) fileNodes.ToArray(typeof(WindowsFileNode));
		}

		public override FileNode[] GetFiles(DirectoryList list, System.IO.TextWriter clientOutput, System.IO.TextWriter serverOutput)
		{
			byte[] dirList = list.GetList(DirectoryName, clientOutput, serverOutput);
			ArrayList fileNodes = new ArrayList(FromFtpList(Encoding.ASCII.GetString(dirList), DirectoryName));
			for(int i = 0; i < fileNodes.Count; i++)
				if(!((FileNode) fileNodes[i]).IsDirectory)
					fileNodes.RemoveAt(i--);
			return (FileNode[]) fileNodes.ToArray(typeof(WindowsFileNode));
		}

		public override string ToString()
		{	//06/06/2003  08:15p      <DIR>          WINNT
			//08/12/2002  10:05p           2,359,352 nightelfboxart-1024x.bmp
			StringBuilder line = new StringBuilder(LastWriteTime.ToString("MM/dd/yyyy  hh:mmt      ").ToLower());
			if(IsDirectory)
				line = line.Append("<DIR>          ");
			else
				line = line.Append(LeftPad(Length.ToString("n", numFormat), 14) + " ");
			line = line.Append(Name);
			return line.ToString();
		}

		public override object Clone()
		{
			return new WindowsFileNode(this);
		}

		private static System.Globalization.NumberFormatInfo numFormat;
	}
}

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions