How do I automatically delete tempfiles in c#?

后端 未结 9 1696
旧巷少年郎
旧巷少年郎 2020-12-04 11:35

What are a good way to ensure that a tempfile is deleted if my application closes or crashes? Ideally I would like to obtain a tempfile, use it and then forget about it.

9条回答
  •  甜味超标
    2020-12-04 11:38

    I would use the .NET TempFileCollection class, as it's built-in, available in old versions of .NET, and implements the IDisposable interface and thus cleans up after itself if used e.g. in conjunction with the "using" keyword.

    Here's an example that extracts text from an embedded resource (added via the projects property pages -> Resources tab as described here: How to embed a text file in a .NET assembly?, then set to "EmbeddedResource" in the embedded file's property settings).

        // Extracts the contents of the embedded file, writes them to a temp file, executes it, and cleans up automatically on exit.
        private void ExtractAndRunMyScript()
        {
            string vbsFilePath;
    
            // By default, TempFileCollection cleans up after itself.
            using (var tempFiles = new System.CodeDom.Compiler.TempFileCollection())
            {
                vbsFilePath= tempFiles.AddExtension("vbs");
    
                // Using IntelliSense will display the name, but it's the file name
                // minus its extension.
                System.IO.File.WriteAllText(vbsFilePath, global::Instrumentation.Properties.Resources.MyEmbeddedFileNameWithoutExtension);
    
                RunMyScript(vbsFilePath);
            }
    
            System.Diagnostics.Debug.Assert(!File.Exists(vbsFilePath), @"Temp file """ + vbsFilePath+ @""" has not been deleted.");
        }
    

提交回复
热议问题