System.IO.IOException: "The file exists" when using System.IO.Path.GetTempFileName() - resolutions?

One of my customers got an exception whenever he tried to use my product. I obtained the callstack of the exception that had occurred, the top of which is:

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.__Error.WinIOError()
   at System.IO.Path.GetTempFileName()
   at System.Windows.Input.Cursor.LoadFromStream(Stream cursorStream)
   at System.Windows.Input.Cursor..ctor(Stream cursorStream)

Googling this, I found plenty of blog posts stating this exception is thrown when there are more than 65535 temp files in the %TEMP% folder, and that the solution is to simply clear out the old temp files. I can ask the customer to do that, but this might only be a temporary solution - what if they are regularly running some other piece of software that makes frequent calls to GetTempFileName, which will make the problem reoccur over and over?

I can't just programmatically clear out the %TEMP% folder, as that might somehow damage something else, and I can't avoid calling GetTempFileName (and using my own temp folder instead) as it's not me but WPF code that's calling it.

Is there any permanent solution for this?

UPDATE: I've confirmed that the problem where the %TEMP% folder is overflowing with log files is not caused by my own code, and must be caused by some other 3rd party application on the customer's machine. I also looked into the implementation of Cursor.LoadFromStream and it surely isn't at fault - it generates a temp file, but then deletes it in finally block.


As I mentioned in my last comment I think your only safe way to do this is to ask the user if they want you to delete files and try again. It is imperative that you get the users input into this, this way it is at their own peril. In my head its something similar to.

public Stream GetStream(Stream cursorStream)
{
    try
    {
       //getting stream
    }
    catch(IOE)
    {
        MessageBox.Show(this, "Unable to get stream, your temporary
                              folder may be full, do you want to try deleting 
                                some and try again?");
         if(yes)
         try
         {
             //delete and try again
             return GetStream(cursorStream);
         }
         catch(IOE)
          {
                //no luck
           }
          else
              return null;
    }

}

An optional check to make sure could be,

Directory.EnumerateFiles(Path.GetTempPath(), "*", SearchOption.TopLevelOnly)
  .Count() == ushort.MaxValue;

Handling I/O errors in .NET, Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place? private static bool modifyFile(FileInfo file, string  System.IO.IOException Member Details Overloaded ctor #1 Summary Initializes a new instance of the IOException class with its message string set to the empty string (""), its HRESULT set to COR_E_IO, and its inner exception set to a null reference. Default constructor.


System.IO.IOException: file used by another process, IO.IOException Class. Assembly: Mscorlib.dll. Namespace: System.IO. Summary: The exception that is thrown when an I/O error  System.IO.IOException, the base class of all System.IO exception types. It is thrown for errors whose return codes from the operating system don't directly map to any other exception type.


Here's the code I used in the end, and put early in my app's initialization code-path, before any calls to Cursor.LoadFromStream might occur:

    private void WarnUserIfTempFolderFull()
    {
        string tempFile = null;
        try
        {
            tempFile = Path.GetTempFileName();
        }
        catch (IOException e)
        {
            string problem = "The Temporary Folder is full.";

            string message = "{ProductName} has detected that the Windows Temporary Folder is full. \n" + 
                             "This may prevent the {ProductName} from functioning correctly.\n" + 
                             "Please delete old files in your temporary folder (%TEMP%) and try again.";

            Logger.Warn(problem);

            MessageBox.Show(message, caption: problem);
        }
        finally
        {
            if (tempFile != null) File.Delete(tempFile);
        }
    }

System.IO.IOException, IOException is the base class for exceptions thrown while accessing information using streams, files and directories. [Note: The Base Class Library includes the  These are unavoidable side effects of the C-Sharp API’s implementation, which keeps a blocking read waiting for data on the socket connection: closing the connection causes the read call to throw a System.IO.IOException, which Visual Studio reports even though it is ‘swallowed’ and not passed through to the API user.


Solutions:

  1. The right one. Detect which application is producing so many temporary files and not deleting them. Utilities like Process monitor should help you. Then either fix the application or throw it away. And yes, this might be your application. that's why I'd recommend you to detect the source of evil.
  2. The easiest one. Use your own temporary directory. This won't help if the files are being created from your code.
  3. The ugliest one. Clear the temporary directory from your application. You're absolutely right about the consequences - you could break another application.

System.IO.IOException Class, I get the following exception: "An unhandled exception of type 'System.IO.​IOException' occurred in mscorlib.dll Additional information: The  I don't know if my stack trace will help. I'm running a DotNet Core 2.1.2 app in Linux docker container on Kubernetes accessing Azure SQL. If this is noise, feel free to delete my comment.


As Sayse suggested, you might try setting the %TEMP% environment variable when your app launches.

Environment.SetEnvironmentVariable("TEMP", "<dir>");

[RESOLVED] System.IO.IOException-VBForums, C# program that handles IOException using System; using System.IO; class Program { static void Main() { try { File.Open("C:\\nope.txt", FileMode.Open); } catch  [RESOLVED] System.IO.IOException Hey, my program reads the contents of various text files and displays the contents in a RichTextBox, but I'm having a problem where I


C# IOException Type: File, Directory Not Found, Exception thrown: 'System.IO.IOException' in System.dll. Bruno Voisin. 10/10/18 #​40856. Has any one come across that error ? It looks unconspicuous and  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.


Exception thrown: 'System.IO.IOException' in System.dll, In VS I can run these in parallel using NUnit's [Parallelizable] attribute without issue, however in Rider I get the following exception: System.IO. @knadt I closed this this because the OP had not responded for a while and others were able to resolve their issues. If you're seeing something similar and the above does not help, recommend reaching out to our support team so that look at your account specifically.


System.IO.IOException when running tests in parallel – JetBrains , The image is probably locked, see answer here: c# - Delete an image being used by another process - Stack Overflow[^] And here for VB: The  Hello. After I upgraded to Windows 10 I've been having a frequent crash while playing Terraria. It happens after I play for a long while, I'd say at least after 1h of play time but it could last until 3h, happening anywhere in that time frame. After researching for a while about Terraria