Skip to main content
added semantic details of GetTempFileName method
Source Link
Fil
  • 1.1k
  • 13
  • 32

I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method (the fileName is the name of a new file created) adding the extension preferred.

string GetNewTempFile(string extension) { if (!extension.StartWith(".")) extension="." + extension; string fileName; bool bCollisions = false; do { fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension); try { using (new FileStream(fileName, FileMode.CreateNew)) { } bCollisions = false; } catch (IOException) { bCollisions = true; } } while (bCollisions); return fileName; } 

I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method.

string GetNewTempFile(string extension) { if (!extension.StartWith(".")) extension="." + extension; string fileName; bool bCollisions = false; do { fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension); try { using (new FileStream(fileName, FileMode.CreateNew)) { } bCollisions = false; } catch (IOException) { bCollisions = true; } } while (bCollisions); return fileName; } 

I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method (the fileName is the name of a new file created) adding the extension preferred.

string GetNewTempFile(string extension) { if (!extension.StartWith(".")) extension="." + extension; string fileName; bool bCollisions = false; do { fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension); try { using (new FileStream(fileName, FileMode.CreateNew)) { } bCollisions = false; } catch (IOException) { bCollisions = true; } } while (bCollisions); return fileName; } 
Source Link
Fil
  • 1.1k
  • 13
  • 32

I mixed @Maxence and @Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method.

string GetNewTempFile(string extension) { if (!extension.StartWith(".")) extension="." + extension; string fileName; bool bCollisions = false; do { fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension); try { using (new FileStream(fileName, FileMode.CreateNew)) { } bCollisions = false; } catch (IOException) { bCollisions = true; } } while (bCollisions); return fileName; }