Windows Phone Developers

Thursday, October 30, 2008

C# Get Temporary File / Store Values in Temporary files using C# (.NET)

C# Get Temporary File / Store Values in Temporary files using C# (.NET)

Many times in VB we would have used Open...Print...Close to open and write to a text file for temporary storage and use a unique file number to work on those files (Print #1, “Hello” etc). If we use the same number that is already in use, we would get File Open exceptions. To avoid, VB and VBA we used FreeFile to get the free buffer.

Similar way we can use GetTempFileName method to get a temporary file. This method creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file, which can be used to write temporary strings/vars.

// DotNetDud GetTempFileName Example

try

{

String sFile;

sFile = Path.GetTempFileName();

Console.WriteLine("Temporary File " + sFile);

//Store the Values Temporarily in Temp file

StoreVar(sFile);

}

catch (IOException ex1)

{

Console.WriteLine ("IOException " + ex1.Message);

}

catch (Exception ex2)

{

Console.WriteLine("Unhandled Exception " + ex2.Message);

}

If you want to have cryptographically strong, random string that can be used as either a folder name or a file name use the following:

sFile = Path.GetRandomFileName();

This does not create a file/folder, you need to write separate code to create the file. You can use GetTempFolder method () to get the temporary folder and create the file there.

Freefile in .NET (C#), .NET Create Temporary Files, Temporary Files in .NET (C#), C# Path Class, C# GetTempFileName method, .Net GetTempFileName method Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

1 comment:

  1. Thanks for the code!
    btw...technically the string "Unhandled Exception" in your function isnt accurate since you are using a catch block to catch the exception, you are, in fact, handling the exception. A more accurate string might be "General Exception". Just my two cents!

    ReplyDelete