Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Reflection;
- namespace System.IO
- {
- /*
- //Example
- //creates temp folder in User/Temp with the assembly name
- using(TempFileManager tmgr = new TempFileManager(".txt")) {
- File.WriteAllText(tmgr.GetTempFilename(),"Test");
- }//deletes temp folder upon Dispose()
- * */
- /// <summary>
- /// Creates and cleans up a temp folder and temp filenames.
- /// </summary>
- public class TempFileManager:IDisposable
- {
- string _extension;
- string _folder;
- static int _counter = 0;
- /// <summary>
- /// Creates a folder with the entry assembly's name in the user's Temp folder
- /// and creates temp files with a .tmp extension.
- /// </summary>
- /// <remarks>T</remarks>
- public TempFileManager() : this(".temp") { }
- /// <summary>
- /// Creates a folder with the name <ApplicationName>Temp in the user's Temp folder
- /// and creates temp files with the given extension.
- /// </summary>
- public TempFileManager(string extension) : this(GetAssemblyName(),extension) { }
- /// <summary>
- /// Creates a folder with the given name in the user's Temp folder
- /// and creates temp files the given extension.
- /// </summary>
- public TempFileManager(string folderName,string extension)
- {
- _folder = Path.Combine(Path.GetTempPath(),folderName);
- _extension = extension;
- Directory.CreateDirectory(_folder);
- }
- static string GetAssemblyName()
- {
- return Assembly.GetEntryAssembly().GetName().Name;
- }
- /// <summary>
- /// Gets a temp filename.
- /// </summary>
- /// <returns>A string containing the temp filename.</returns>
- public string GetTempFilename()
- {
- return GetTempFilename(_extension);
- }
- /// <summary>
- /// Gets a temp filename.
- /// </summary>
- /// <param name="extension">The extension for the temp file.</param>
- /// <returns>A string containing the temp filename.</returns>
- public string GetTempFilename(string extension)
- {
- return Path.Combine(_folder,_counter++ + extension);
- }
- /// <summary>
- /// Deletes the temp folder and all files within.
- /// </summary>
- /// <param name="throwException">Indicates if any exceptions occurring while deleting should
- /// be thrown or suppressed.</param>
- public void DeleteFolder(bool throwException)
- {
- try
- {
- Directory.Delete(_folder,true);
- }
- catch
- {
- if(throwException)
- {
- throw;
- }
- }
- }
- /// <summary>
- /// Deletes the temp folder and all files within. Any exceptions thrown are suppressed.
- /// If you want to handle any exceptions, call DeleteFolder(true);
- /// </summary>
- public void Dispose()
- {
- GC.SuppressFinalize(this);
- DeleteFolder(false);
- }
- ~TempFileManager()
- {
- DeleteFolder(false);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment