Posts Tagged ‘ microsoft ’

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

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