Archive for August, 2010

Recursively Search Directories


Listing files from directories and sub-directories is a common requirement for many developers. In this short tutorial I will show you how to do this in two different ways.

The Directory.GetFiles() Method

This first method is by far the easier of the two, but to implement this you must be working with Microsoft .NET Framework version 2.0 or later.

The System.IO.Directory class contains a method called GetFiles(). It returns a string array of full file names for each file it finds. It also accepts a number of parameters which allow you to customize your search. Below are examples of the three overloads for GetFiles().

Here we are getting a string array of all the files within the directory “E:\Music\Dire Straits”.

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits");

Now here we are filtering which files to get by file extension – we are getting only the files with an extension of “.mp3″ from “E:\Music\Dire Straits.”

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits", "*.mp3");

Finally here we are getting all the “.mp3″ files from “E:\Music\Dire Straits” and all its sub-directories.

string[] files = Directory.GetFiles("E:\\Music\\Dire Straits",
                                    "*.mp3",
                                    SearchOption.AllDirectories);

As you can see, the guys from Microsoft have made getting files from directories recursively very easy – it is just one line of code!

Create a Recursive Search Method

If you are running Microsoft .NET Framework 1.1 you will have to create your own method to recursively search your directory since the GetFiles() method does not support the SearchOption overload.

A recursive method is basically a method which calls itself. Recursion is a very useful technique but can also be demanding on memory if the recursion gets too deep.

So, let’s create a recursive method which will search for all “mp3″ files within a given directory and its sub-directories.

private void DirSearchMP3(string directory)
{
    foreach (string dir in Directory.GetDirectories(directory))
    {
        foreach (string file in Directory.GetFiles(dir, "*.mp3"))
        {
            this.files.Add(file);
        }

        this.DirSearchMP3(dir);
    }
}

As you can see in the above example, we are iterating all the directories within the given directory passed as a parameter, and then searching for “.mp3″ files within each directory. Then the DirSearchMP3() method calls itself and starts the whole process again. It keeps doing this until no more sub-directories are found.

Below is the whole file listing for this example.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

namespace RecursiveFileSearch
{
    public partial class Form1 : Form
    {
        List files = new List();

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            // Search for mp3 files within all sub-directories directories
            this.DirSearchMP3("E:\\Music\\Dire Straits");

            // Search for mp3 files within current directory
            foreach (string file in Directory.GetFiles("E:\\Music\\Dire Straits", "*.mp3"))
            {
                this.files.Add(file);
            }

            // Display all files found
            foreach (string file in this.files)
            {
                Console.WriteLine(file);
            }
        }

        private void DirSearchMP3(string directory)
        {
            foreach (string dir in Directory.GetDirectories(directory))
            {
                foreach (string file in Directory.GetFiles(dir, "*.mp3"))
                {
                    this.files.Add(file);
                }

                this.DirSearchMP3(dir);
            }
        }
    }
}

As you can see from this small tutorial, recursively searching directories is much easier with the .NET 2.0 framework.
Paul

Advertisements

How to use Temporary Files in C#


What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing ‘work data‘. For example Microsoft Office uses temp files to store backups of documents being created or edited. Other applications might use temp files to store large amounts of data which would otherwise occupy too much memory. Basically, it is up to the developer to decide what should be kept within his/her application’s temp files.

In Microsoft Windows, temp files end with the .tmp extension and by default are stored in C:\Users\[username]\AppData\Local\Temp.

The .NET Framework makes creating and using temp files a breeze, so let me show you how to use them.

Create a new Console Application and add a method called CreateTmpFile. In this method we will use the System.IO.Path class to create our temp file.

private static string CreateTmpFile()
{
    string fileName = string.Empty;

    try
    {
        // Get the full name of the newly created Temporary file.
        // Note that the GetTempFileName() method actually creates
        // a 0-byte file and returns the name of the created file.
        fileName = Path.GetTempFileName();

        // Craete a FileInfo object to set the file's attributes
        FileInfo fileInfo = new FileInfo(fileName);

        // Set the Attribute property of this file to Temporary.
        // Although this is not completely necessary, the .NET Framework is able
        // to optimize the use of Temporary files by keeping them cached in memory.
        fileInfo.Attributes = FileAttributes.Temporary;

        Console.WriteLine("TEMP file created at: " + fileName);
    }
    catch (Exception ex)
    {
       Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
    }

    return fileName;
}

As you can see in the above code we are calling the GetTempFileName method of the Path class to create our temp file. When called, this method will automatically create the temp file in the correct folder according to your version of Windows. Then we are creating a FileInfo object and setting the Temporary attribute of our temp file. You can work without setting this attribute, but it is recommended to set it since the .NET Framework will optimize the way it uses your temp file if set.

And that’s all you need to do to create a temp file. The temp file’s name is automatically generated and looks something like this: tmpBD28.tmp.

Now let’s write some data to our temp file:

private static void UpdateTmpFile(string tmpFile)
{
    try
    {
        // Write to the temp file.
        StreamWriter streamWriter = File.AppendText(tmpFile);
        streamWriter.WriteLine("Hello from Paul Mercieca");
        streamWriter.Flush();
        streamWriter.Close();

        Console.WriteLine("TEMP file updated.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error writing to TEMP file: " + ex.Message);
    }
}

As you can see all we are doing here is opening the temp file using the StreamWriter class and then writing to it. It’s just like writing to a normal text file.

To read from the temp file is quite similar:

private static void ReadTmpFile(string tmpFile)
{
    try
    {
        // Read from the temp file.
        StreamReader myReader = File.OpenText(tmpFile);
        Console.WriteLine("TEMP file contents: " + myReader.ReadToEnd());
        myReader.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading TEMP file: " + ex.Message);
    }
}

Once you’re done using the temp file you need to delete it or else it will obviously remain there, and over time these files will end up filling your temp folder.

private static void DeleteTmpFile(string tmpFile)
{
    try
    {
        // Delete the temp file (if it exists)
        if (File.Exists(tmpFile))
        {
            File.Delete(tmpFile);
            Console.WriteLine("TEMP file deleted.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error deleteing TEMP file: " + ex.Message);
    }
}

Once you create all the above methods, you can call them for testing purposes as shown below:

static void Main(string[] args)
{
    string tmpFile = CreateTmpFile();
    UpdateTmpFile(tmpFile);
    ReadTmpFile(tmpFile);
    DeleteTmpFile(tmpFile);

    Console.ReadLine();
}

Another useful method within the Path class is the GetTempPath() method. This returns the path of the current system’s temporary folder, which you might want when working with temp files.

I hope you found this article useful. Feel free to add comments or ask any questions below.
Paul

ASP.NET Postback Class Members


Basically I had a class variable in an ASP.NET and found it was getting lost on page post-back.. well all you have to do is put that object in the Viewstate object already created for you.

public partial class MyPage : System.Web.UI.Page
{
        protected int MyInt;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
		MyInt = 12345;
                ViewState["MyKey"] = MyInt;
            }
        }

        /*
	 This is called on a page post-back...
	*/
	protected void Event(object sender, EventArgs e)
        {
			//Get factor list from viewstate
			MyInt = (int)ViewState["MyKey"];

			//Go nuts
	}
}

Code For Export Data From DataGrid to Excel Sheet with C#


public static void ExportDataGridToExcel(DataGrid dgrdExport,Page pg)
		{
			try
			{
				pg.Response.Clear();
				pg.Response.Buffer= true;
				pg.Response.ContentType = "application/vnd.ms-excel";
				pg.Response.Charset = "";
				pg.EnableViewState = false;
				System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
				System.Web.UI.HtmlTextWriter oHtmlTextWriter = new                				System.Web.UI.HtmlTextWriter(oStringWriter);
             			ClearControls(dgrdExport);
				dgrdExport.RenderControl(oHtmlTextWriter);
				pg.Response.Write(oStringWriter.ToString());
				pg.Response.End();
			}
			catch(System.Exception ex)
			{
				throw ex;
			}

		}

Code For Clear Controls from form

private static void ClearControls(Control control)
		{
			for (int cnt=control.Controls.Count -1; cnt>=0; cnt--)
			{
				ClearControls(control.Controls[cnt]);
			}
			if (!(control is TableCell))
			{
					if (control.GetType().GetProperty("SelectedItem") != null)
					{
						LiteralControl literal = new LiteralControl();
						control.Parent.Controls.Add(literal);
						try
						{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);
						}
						catch
						{

						}
						control.Parent.Controls.Remove(control);
					}

					else

					if (control.GetType().GetProperty("Text") != null)
					{
						LiteralControl literal = new LiteralControl();
						control.Parent.Controls.Add(literal);

literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null);
						control.Parent.Controls.Remove(control);
					}
			}
			return;
		}

Shutdown or Restart the Computer Using C#


The easiest way to shutdown, restart, or hibernate a computer programmatically using C# is to use the shutdown command-line tool that comes with Windows. This tool has a lot of options, for example /l logs of the user, /s shuts down the computer, /r restarts the computer, and /h hibernates the computer. To get the full list of available options, type help shutdown in the Command Prompt.
To execute shutdown from C# use the follow statement:

//the first parameter is the command, and the second is its arguments
System.Diagnostics.Process.Start("shutdown", "/s");

Drag And Drop Files to a C# Application


The .NET Framework makes it easy to detect objects dragged and/or dropped into a Windows Forms application using one or more of the drag-and-drop events available. In these events you could check if the object is a file.

To enable a control to be a target of a drag-and-drop operation set its AllowDrop property to true and use one or more of the following events:

  • DragEnter: Occurs when the user drags an object into the control’s area, and has not released the mouse button yet.
  • DragOver: Occurs when the object is being dragged in the control’s area.
  • DragDrop: Occurs when the user lets go of the dragged object in the control’s area.
  • DragLeave: Occurs if the object dragged into the control is dragged out again without the user releasing the mouse button, or the user canceled the operation by pressing the Escape key.
  • GiveFeedback: Occurs when the drag-and-drop operation starts and is used to modify the visual feedback of the operation.
  • QueryContinueDrag: Occurs when the keyboard or mouse state is changed during the drag-and-drop operation.

To process one or more files dragged and dropped into a control two events are needed, DragEnter and DragDrop. The if statement in DragEnter checks what is dragged in is of type DataFormats.FileDrop, the Windows file drop format, or not. If true the drag operation is allowed. The DragDrop event retrieves the list of files dropped using the GetData method and casts them to an array of strings. Each element of the array will contain a full path of one of the files dropped.

private void filesListBox_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
    {
        e.Effect = DragDropEffects.All;
    }
}  

private void filesListBox_DragDrop(object sender, DragEventArgs e)
{
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);  

    foreach (string file in files)
    {
        filesListBox.Items.Add(file);
    }
}