Hi,

I want to open a text file and read the data then sort it via date.

i found some stuff already that helps but im new to this and if anyone point me in the right direction it would be very appreciated.

this sample app here http://www.c-sharpcorner.com/UploadFile/mmehta/OpeningandViewingTextandImageFiles12082005060630AM/OpeningandViewingTextandImageFiles.aspx

opens the text file exactly how i want it to, i would just like to have the data sorted by date also. And eventually i would like to add color coding to the IP's and 32 digit numbers.

here is a sample of what the text file would look like....

[08.28.2007 00:47:19] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.28.2007 03:02:29] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.28.2007 03:13:04] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.28.2007 06:36:17] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.29.2007 04:11:11] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.29.2007 10:57:30] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 202.60.65.6
[08.29.2007 13:19:06] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[08.30.2007 12:45:50] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[08.31.2007 13:06:59] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[09.01.2007 12:38:27] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[09.02.2007 05:58:45] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 85.25.130.10
[09.02.2007 07:38:52] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[09.02.2007 11:01:58] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127
[09.02.2007 12:44:47] PlayerIP: 62.165.245.133 00f55c74a4dd5b5845a9b870edcff175 ServerIP: 195.149.21.127

any help is greatly appreciated

Recommended Answers

All 12 Replies

Hi, if every line starts with the date, this should do the trick:

List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\data.txt", FileMode.Open)))
{
	string line;
	while ((line = r.ReadLine()) != null)
	{
		lines.Add(line);
	}
				
}
lines.Sort();

where exactly would i add this....im assuming this file somewhere;;;

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Resources;

namespace FileDisplay
{
	//windows_forms inherits from the Form class
	public class windows_forms : Form //class in System.Windows.Forms 
	{
		// Container is the class in System.ComponentModel namespace
		private Container components; 

		//MenuItem is the class in System.Windows.Forms namespace
		private MenuItem file;
		private MenuItem openfile;
		private MenuItem openTextfile;
		private MenuItem openImagefile;
		private MenuItem closefile;
		private MenuItem exit;
		private MenuItem help;
		private MenuItem abouthelp; 
		
		//MainMenu is the class in System.Windows.Forms namespace
		private MainMenu mainMenu1;

		//RichTextBox, PictureBox, Panel are the classes in System.Windows.Forms namespace
		private RichTextBox fileLoadArea;
		private PictureBox pictureBox1 ;
		private Panel mainPanel;


		public windows_forms() //constructor
		{
			InitializeComponent();
			
		}

		private void InitializeComponent()
		{
			//initializing the classes
			this.mainMenu1 = new MainMenu();

			this.file = new MenuItem();
			this.openfile = new MenuItem();
			this.openTextfile = new MenuItem();
			this.openImagefile = new MenuItem();
			this.closefile = new MenuItem();
			this.exit = new MenuItem();

			this.help = new MenuItem();
			this.abouthelp= new MenuItem();
			
			this.fileLoadArea = new RichTextBox();
			this.pictureBox1 = new PictureBox();

			this.mainPanel = new Panel();
			
			this.SuspendLayout();
			 
	 
			// mainMenu1
				this.mainMenu1.MenuItems.AddRange(new MenuItem[] 
														{
															  this.file,
															  this.help
														});
				// file
				this.file.Index = 0;
				this.file.MenuItems.AddRange(new MenuItem[] 
														{
															this.openfile,
															this.closefile,
															this.exit
														});
				this.file.Text = "File";
			
					// openfile
					this.openfile.Index = 0;
					this.openfile.MenuItems.AddRange(new MenuItem[] 
														{
														  this.openTextfile,
														 this.openImagefile
														});
						this.openfile.Text = "OpenFile";
			
						// openTextfile
						this.openTextfile.Index = 0;
						this.openTextfile.Text = "OpenTextFile...";
						this.openTextfile.Click += new System.EventHandler(this.onFileOpen);
                        
			 
						// openImagefile
						this.openImagefile.Index = 1;
						this.openImagefile.Text = "&OpenImageFile...";
						this.openImagefile.Click += new System.EventHandler(this.onImageOpen);
			
					// closefile
					this.closefile.Index = 1;
					this.closefile.Text = "CloseFile";
					this.closefile.Click += new System.EventHandler(this.onFileClose);
			
					// exit
					this.exit.Index = 2;
					this.exit.Text = "exit";
					this.exit.Click += new System.EventHandler(this.onWindowClose);
			
				// help
				this.help.Index = 1;
				this.help.MenuItems.AddRange(new MenuItem[] 
														{
															 this.abouthelp
														});
				this.help.Text = "Help";

					// abouthelp
					this.abouthelp.Index = 0;
					this.abouthelp.Text = "Learning .NET";
					 
			// fileLoadArea
			 	this.fileLoadArea.Dock = DockStyle.Fill;
				this.fileLoadArea.Name = "fileLoadArea";
				this.fileLoadArea.Size = new Size(600, 400);
				this.fileLoadArea.Text = "";
				 
			// pictureBox1
			this.pictureBox1.Location = new Point(32, 40);
			this.pictureBox1.Name = "pictureBox1";
			this.pictureBox1.Size = new Size(600,400);
				
			 
			// mainPanel
			//Control class is in System.Windows.Forms namespace
			this.mainPanel.Controls.AddRange(new Control[] 
															{
																this.fileLoadArea,
																this.pictureBox1
															});
			this.mainPanel.Dock = DockStyle.Fill;
			this.mainPanel.Name = "mainPanel";
			this.mainPanel.Size = new Size(600, 400);
						 
			// windows_forms
				this.ClientSize = new System.Drawing.Size(600, 500);
				this.Controls.AddRange(new Control[] 
												{
														this.mainPanel
												});
				this.Menu = this.mainMenu1;
				this.Name = "windows_forms";
				this.Text = "Learning Windows Forms";
				mainPanel.Hide();
				this.ResumeLayout();
		}

   		
		// Handler for the TextFileOpen command
			private void onFileOpen (object sender, EventArgs e)
			{
				if( pictureBox1 !=null)
					pictureBox1.Hide();

				fileLoadArea.Text ="";
				mainPanel.Show();
				fileLoadArea.Show();

				OpenFileDialog openFileDialog1 = new OpenFileDialog();
				openFileDialog1.InitialDirectory = "d:\\" ;
				openFileDialog1.RestoreDirectory = true ;
				openFileDialog1.Filter = 
					"Text Files (*.txt)|*.txt|Rich Text Format (*.rtf)|*.rtf)|"+
					" All Files (*.*)|*.*";

				if (openFileDialog1.ShowDialog () == DialogResult.OK) 
				{
					String fileName = openFileDialog1.FileName;
					if (fileName.Length != 0) 
					{
						try 
						{
							ReadFileInfo(fileName);
						}
						catch 
						{
							MessageBox.Show (String.Format ("{0} is not " +
							"a valid image file", fileName), "Error",
							MessageBoxButtons.OK , MessageBoxIcon.Error);
						}
					}
				}
			}

		private void ReadFileInfo(String filename)
			{
				try 
				{
					FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
					FileInfo fInfo = new FileInfo(filename);
					string fext = fInfo.Extension.ToUpper();
					if (fext.Equals(".RTF"))
						fileLoadArea.LoadFile(fs, RichTextBoxStreamType.RichText);
					else
						fileLoadArea.LoadFile(fs, RichTextBoxStreamType.PlainText);
					fs.Close();
				}
				catch(Exception e)
				{
					Console.WriteLine("Exception"+e.StackTrace);
				}
			}


			// Handler for the ImageFileOpen command
			private void onImageOpen (object sender, EventArgs e)
			{
				if (fileLoadArea !=null)
				{
					fileLoadArea.Hide();
				}
				mainPanel.Show();
								
				OpenFileDialog ofd = new OpenFileDialog ();
				ofd.Filter = "Image Files (*.bmp)|*.bmp|JPEG Files (*.jpeg)|*.jpeg|"+
							" All Files (*.*)|*.*";
				if (ofd.ShowDialog () == DialogResult.OK) 
				{
					String fileName = ofd.FileName;
					if (fileName.Length != 0) 
					{
						try 
						{
							pictureBox1.BackgroundImage = new Bitmap(fileName);
							pictureBox1.Show();
						}
						catch 
						{
							MessageBox.Show (String.Format ("{0} is not " +
							"a valid image file", fileName), "Error",
							MessageBoxButtons.OK , MessageBoxIcon.Error);
						}
					}
				}
			}

		
			// method to drive the File/Close button
			private void onFileClose (object sender, System.EventArgs e)
			{
					mainPanel.Hide();
			}

					
		// method to drive the Window/Close button
		private void onWindowClose (object sender, System.EventArgs e)
		{
			// Handler for the Close command
				Close ();
		}

		public static void Main(string[] args) 
		{
			Application.Run(new windows_forms());
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
				
			}
			base.Dispose( disposing );
		}

	}
}

sorry im very noobish at this....

Anyone got any ideas on this one

I think _r0ckbaer answered you!!

i also have a second question

its after his answer in case you missed it.....

Member Avatar for iamthwee

>if every line starts with the date

Not entirely sure if that would work all the time, especially seeing as some dates can be written as DD-MM-YYYY or YYYY-MM-DD etc. A cast iron solution would be to convert the date to a date object and use the sort methods associated with that.

the date format is always the same for what i am doing...

e.g.

MM-DD-YYYY

Member Avatar for iamthwee

the date format is always the same for what i am doing...

e.g.

MM-DD-YYYY

in that case _r0ckbaer's solution will fail.

I am so close its not funny........

ive done what you suggested and when i build the application and try to open a text file it says this is not a valid image.the only message i get in express is;

Field 'FileDisplay.windows_forms.components' is never assigned to, and will always have its default value null

Ill inlcude the code to show you what i have

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Collections.Generic;

namespace FileDisplay
{



    // create a class to compare lines by date
    public class LineComparer : IComparer<string>
    {

        public int Compare(string s1, string s2)
        {
            string dateFormat = "MM.dd.yyyy HH:mm:ss";
            DateTime dt1 = DateTime.ParseExact(s1.Substring(1, 19), dateFormat, null);
            DateTime dt2 = DateTime.ParseExact(s2.Substring(1, 19), dateFormat, null);
            if (dt1 == dt2)
                return 0;
            else if (dt1 < dt2)
                return -1;
            else
                return 1;
        }
    }
    //windows_forms inherits from the Form class
    public class windows_forms : Form //class in System.Windows.Forms
    {
        // Container is the class in System.ComponentModel namespace
        private Container components;

        //MenuItem is the class in System.Windows.Forms namespace
        private MenuItem file;
        private MenuItem openfile;
        private MenuItem openTextfile;
        private MenuItem openImagefile;
        private MenuItem closefile;
        private MenuItem exit;
        private MenuItem help;
        private MenuItem abouthelp;
        
        //MainMenu is the class in System.Windows.Forms namespace
        private MainMenu mainMenu1;

        //RichTextBox, PictureBox, Panel are the classes in System.Windows.Forms namespace
        private RichTextBox fileLoadArea;
        private PictureBox pictureBox1 ;
        private Panel mainPanel;


        public windows_forms() //constructor
        {
            InitializeComponent();
           
        }

        private void InitializeComponent()
        {
            //initializing the classes
            this.mainMenu1 = new MainMenu();

            this.file = new MenuItem();
            this.openfile = new MenuItem();
            this.openTextfile = new MenuItem();
            this.openImagefile = new MenuItem();
            this.closefile = new MenuItem();
            this.exit = new MenuItem();

            this.help = new MenuItem();
            this.abouthelp= new MenuItem();
           
            this.fileLoadArea = new RichTextBox();
            this.pictureBox1 = new PictureBox();

            this.mainPanel = new Panel();
           
            this.SuspendLayout();
             
     
            // mainMenu1
                this.mainMenu1.MenuItems.AddRange(new MenuItem[]
                                                        {
                                                              this.file,
                                                              this.help
                                                        });
                // file
                this.file.Index = 0;
                this.file.MenuItems.AddRange(new MenuItem[]
                                                        {
                                                            this.openfile,
                                                            this.closefile,
                                                            this.exit
                                                        });
                this.file.Text = "File";
           
                    // openfile
                    this.openfile.Index = 0;
                    this.openfile.MenuItems.AddRange(new MenuItem[]
                                                        {
                                                          this.openTextfile,
                                                         this.openImagefile
                                                        });
                        this.openfile.Text = "OpenFile";
           
                        // openTextfile
                        this.openTextfile.Index = 0;
                        this.openTextfile.Text = "OpenTextFile...";
                        this.openTextfile.Click += new System.EventHandler(this.onFileOpen);
             
                        // openImagefile
                        this.openImagefile.Index = 1;
                        this.openImagefile.Text = "&OpenImageFile...";
                        this.openImagefile.Click += new System.EventHandler(this.onImageOpen);
           
                    // closefile
                    this.closefile.Index = 1;
                    this.closefile.Text = "CloseFile";
                    this.closefile.Click += new System.EventHandler(this.onFileClose);
           
                    // exit
                    this.exit.Index = 2;
                    this.exit.Text = "exit";
                    this.exit.Click += new System.EventHandler(this.onWindowClose);
           
                // help
                this.help.Index = 1;
                this.help.MenuItems.AddRange(new MenuItem[]
                                                        {
                                                             this.abouthelp
                                                        });
                this.help.Text = "Help";

                    // abouthelp
                    this.abouthelp.Index = 0;
                    this.abouthelp.Text = "Learning .NET";
                     
            // fileLoadArea
                 this.fileLoadArea.Dock = DockStyle.Fill;
                this.fileLoadArea.Name = "fileLoadArea";
                this.fileLoadArea.Size = new Size(600, 400);
                this.fileLoadArea.Text = "";
                 
            // pictureBox1
            this.pictureBox1.Location = new Point(32, 40);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new Size(600,400);
               
             
            // mainPanel
            //Control class is in System.Windows.Forms namespace
            this.mainPanel.Controls.AddRange(new Control[]
                                                            {
                                                                this.fileLoadArea,
                                                                this.pictureBox1
                                                            });
            this.mainPanel.Dock = DockStyle.Fill;
            this.mainPanel.Name = "mainPanel";
            this.mainPanel.Size = new Size(600, 400);


           


                         
            // windows_forms
                this.ClientSize = new System.Drawing.Size(600, 500);
                this.Controls.AddRange(new Control[]
                                                {
                                                        this.mainPanel
                                                });
                this.Menu = this.mainMenu1;
                this.Name = "windows_forms";
                this.Text = "Learning Windows Forms";
                mainPanel.Hide();
                this.ResumeLayout();
        }

          
        // Handler for the TextFileOpen command
            private void onFileOpen (object sender, EventArgs e)
            {
                if( pictureBox1 !=null)
                    pictureBox1.Hide();

                fileLoadArea.Text ="";
                mainPanel.Show();
                fileLoadArea.Show();

                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.InitialDirectory = "d:\\" ;
                openFileDialog1.RestoreDirectory = true ;
                openFileDialog1.Filter =
                    "Text Files (*.txt)|*.txt|Rich Text Format (*.rtf)|*.rtf)|"+
                    " All Files (*.*)|*.*";

                if (openFileDialog1.ShowDialog () == DialogResult.OK)
                {
                    String fileName = openFileDialog1.FileName;
                    if (fileName.Length != 0)
                    {
                        try
                        {
                            string[] lines = File.ReadAllLines("fileName");
                            LineComparer comparer = new LineComparer();
                            Array.Sort(lines, comparer);
                            //ReadFileInfo(fileName);
                        }
                        catch
                        {
                            MessageBox.Show (String.Format ("{0} is not " +
                            "a valid image file", fileName), "Error",
                            MessageBoxButtons.OK , MessageBoxIcon.Error);
                        }
                    }
                }
            }

        private void ReadFileInfo(String filename)
            {
                try
                {
                    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                    FileInfo fInfo = new FileInfo(filename);
                    string fext = fInfo.Extension.ToUpper();
                    if (fext.Equals(".RTF"))
                        fileLoadArea.LoadFile(fs, RichTextBoxStreamType.RichText);
                    else
                        fileLoadArea.LoadFile(fs, RichTextBoxStreamType.PlainText);
                    fs.Close();
                }
                catch(Exception e)
                {
                    Console.WriteLine("Exception"+e.StackTrace);
                }
            }


            // Handler for the ImageFileOpen command
            private void onImageOpen (object sender, EventArgs e)
            {
                if (fileLoadArea !=null)
                {
                    fileLoadArea.Hide();
                }
                mainPanel.Show();
                               
                OpenFileDialog ofd = new OpenFileDialog ();
                ofd.Filter = "Image Files (*.bmp)|*.bmp|JPEG Files (*.jpeg)|*.jpeg|"+
                            " All Files (*.*)|*.*";
                if (ofd.ShowDialog () == DialogResult.OK)
                {
                    String fileName = ofd.FileName;
                    if (fileName.Length != 0)
                    {
                        try
                        {
                            pictureBox1.BackgroundImage = new Bitmap(fileName);
                            pictureBox1.Show();
                        }
                        catch
                        {
                            MessageBox.Show (String.Format ("{0} is not " +
                            "a valid image file", fileName), "Error",
                            MessageBoxButtons.OK , MessageBoxIcon.Error);
                        }
                    }
                }
            }

       
            // method to drive the File/Close button
            private void onFileClose (object sender, System.EventArgs e)
            {
                    mainPanel.Hide();
            }

                   
        // method to drive the Window/Close button
        private void onWindowClose (object sender, System.EventArgs e)
        {
            // Handler for the Close command
                Close ();
        }

        public static void Main(string[] args)
        {
            Application.Run(new windows_forms());
        }

        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
               
            }
            base.Dispose( disposing );
        }

    }
}

Thanks again..

When you catch the exception you should output its message, and not "blabla..is not a valid image file". That way you'll be able to identify what's going wrong.

Just for the gallery, see first part of code in my previous post:

string format = "MM.dd.yyyy HH:mm:ss";
            lines.Sort(new Comparison<string>(delegate(string a, string b)
                                                  {
                                                      string dateA = Regex.Match(a, "\\[(.+)\\]").Groups[1].Value;
                                                      string dateB = Regex.Match(b, "\\[(.+)\\]").Groups[1].Value;

                                                      return (DateTime.Compare(DateTime.ParseExact(dateA, format, null),
                                                          DateTime.ParseExact(dateB, format, null)));
                                                  }));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.