首页 > 解决方案 > 在 C# 中保护临时文件

问题描述

在 C# 上使用应用程序时,我正在使用以下逻辑创建一些临时文件:

创建临时文件

private static string CreateTmpFile()
{
string fileName = string.Empty;

try
{
    // Get the full name of the newly created Temporary file. 
    // Note that the GetTempFileName() method actually creates
    // a 0-byte file and returns the name of the created file.
    fileName = Path.GetTempFileName();

    // Craete a FileInfo object to set the file's attributes
    FileInfo fileInfo = new FileInfo(fileName);

    // Set the Attribute property of this file to Temporary. 
    // Although this is not completely necessary, the .NET Framework is able 
    // to optimize the use of Temporary files by keeping them cached in memory.
    fileInfo.Attributes = FileAttributes.Temporary;

    Console.WriteLine("TEMP file created at: " + fileName);
}
catch (Exception ex)
{
   Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
}

return fileName;
}

写入临时文件

private static void UpdateTmpFile(string tmpFile)
{
try
{
    // Write to the temp file.
    StreamWriter streamWriter = File.AppendText(tmpFile);
    streamWriter.WriteLine("Hello from www.daveoncsharp.com!");
    streamWriter.Flush();
    streamWriter.Close();

    Console.WriteLine("TEMP file updated.");
}
catch (Exception ex)
{
    Console.WriteLine("Error writing to TEMP file: " + ex.Message);
}
}

我还尝试并遵循了在此链接上找到的一些实现以解决另一个问题 ,并在我的代码中使用以下实现:将文件存储在 AppData 文件夹中以使用 ACL

但是,我被要求确保:

  1. 在应用程序运行期间,任何人(甚至用户)都无法读取临时文件,
  2. 并确保即使在强制关闭应用程序时也将它们删除

对于案例 1:在应用程序运行期间,任何人(甚至用户)都无法读取临时文件,我该如何为我的应用程序文件实现此功能?临时文件包含敏感数据,即使用户自己想阅读也不应该阅读。有没有办法我可以做到这一点?

对于案例 2:确保即使在强制关闭应用程序时也会删除它们在这里我想确保即使强制关闭或突然重新启动文件也会被删除。

如果强制关闭:则在强制关闭之前删除文件

如果重新启动:则在下次启动时删除文件

这些可行吗?

标签: c#

解决方案


推荐阅读