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

Advertisements

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);
    }
}

Check If User Name Exists Using AJAX And C#


You could make sure the user name entered during the registration process of your website is unique before the submit button is clicked using AJAX and C#. To accomplish this create two aspx pages. The first (default.aspx in this example) is the registration page, and it contains a TextBox control with an onkeyup element that calls the updateOutput JavaScript function and a span tag to display the HTML returned by the XMLHttpRequest.send function. The second page (doajaxstuff.aspx) should only contain following tags:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="doajaxstuff.aspx.cs"
  2. Inherits="ManualAJAX.doajaxstuff" %>
  3. <asp:literal runat="server" id="literal1" />

The html, title and body tags should be removed because the page contents will be added to the default.aspx page, which already has these tags. The C# code that checks if the user name exists is in the Page_Load event of doajaxstuff.aspx. It gets the user name from the query string and displays the result in a Literal control. To keep the example simple I returned “User name exists” or “OK”, but this could be changed to return an img tag to show a red cross image or a green tick respectively.

string[] usernames = { "admin", "administrator", "user1","user2",
                     "guest1", "guest2"};
protected void Page_Load(object sender, EventArgs e)
{
    string newUsername = Request.QueryString["q"];  

    if(usernames.Contains(newUsername))
    {
        literal1.Text = "User name exists";
    }
    else
    {
        literal1.Text = "OK";
    }
}

The JavaScript code below does the AJAX work. The updateOutput function checks first if the TextBox is empty, and exits if true. Then it creates an object called xmlHttp which is an XMLHttpRequest object or an ActiveXObject, depending on the user’s browser. XMLHttpRequest is supported in browsers from Internet Explorer 6, Opera 7.60, Mozilla 1.0, Netscape 7, Safari 1.2 and Konqueror 3.2. If the user has Internet Explorer 5 an ActiveXObject will be created, which basically does the same job. If the xmlHttp object is created the variable url will be assigned a string containing the page to call plus the query string, which is the string entered by the user in usernameTextBox.

The onreadystatechange event handler is assigned the name of the function StateChanged. This event occurs five times: when the request is initialized, set up, sent, being processed and completed. You could check which stage the request is in using the readyState variable (0, 1, 2, 3 and 4 respectively.) The if statement checks for 4 which is set when the HTML is downloaded to xmlHttp.responseText. The if statement also makes sure that xmlHttp.status is 200, which means no error occurred. If both these conditions are true the contents of xmlHttp.responseText are displayed in the span tag.

The open method sets the parameters of the request and contains three parameters; the request method, the URL of the request and a Boolean parameter that specifies the request should be executed asynchronously or not. The first parameter could be “GET”, “POST”, “HEAD” or “PUT”. The second parameter is the relative or full URL of the page to request. And the third parameter should be true so the page could be called asynchronously.

The send method executes the request. Because the open method’s first parameter is “GET”, send’s parameter is null. If open’s first parameter was “POST” it would be a string containing the request parameters.

Code:

<head runat="server">
<title>Manual AJAX</title>
<script language="javascript" type="text/javascript">
var xmlHttp;
function updateOutput(inputString)
{
if(inputString.length == 0)
{
document.getElementById("output").innerHTML = "";
return;
}
try
{
if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
if(!xmlHttp || xmlHttp == null)
{
return;
}
var url="doajaxstuff.aspx?q=" + inputString;
xmlHttp.onreadystatechange=StateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
catch(e)
{
document.getElementById("output").innerHTML = "An error occured";
}
}
function StateChanged()
{
if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
{
document.getElementById("output").innerHTML = xmlHttp.responseText;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Username:
<asp:TextBox runat="server" ID="usernameTextBox"
onkeyup="updateOutput(this.value)" />
<span id="output"></span>
</div>
</form>
</body>
<head runat="server">     <title>Manual AJAX</title> <script language="javascript" type="text/javascript">         var xmlHttp; function updateOutput(inputString) {             if(inputString.length == 0)  {                 document.getElementById("output").innerHTML = "";   return;             } try  {                 if(window.XMLHttpRequest)       xmlHttp = new XMLHttpRequest();  else if (window.ActiveXObject)     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");             if(!xmlHttp || xmlHttp == null)  {                     return;                 } var url="doajaxstuff.aspx?q=" + inputString;                 xmlHttp.onreadystatechange=StateChanged;                 xmlHttp.open("GET", url, true);                 xmlHttp.send(null);             }             catch(e)             {                 document.getElementById("output").innerHTML = "An error occured";             }         } function StateChanged() {             if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))  {                 document.getElementById("output").innerHTML = xmlHttp.responseText;             }         }     </script> </head> <body>     <form id="form1" runat="server">     <div>         Enter Username:         <asp:TextBox runat="server" ID="usernameTextBox" onkeyup="updateOutput(this.value)" />         <span id="output"></span>     </div>     </form> </body>

For this example the C# code in the doajaxstuff.aspx page searches an array containing the user names. This could be changed to search through the users in the aspnetdb database using the Membership.GetUser static function. I should also mention that the user can ignore the result of this validation check and submit a name that exists. To prevent this, the same validation should be done in the Submit button’s code.

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);
    }
}