繁体   English   中英

创建并以只读方式打开现有文件的临时副本并在使用后删除

[英]Create and open as read-only a temporary copy of an existing file and delete after use

我已经搜索了信息,但我只是担心我可能会在这里陷入困境,因为我不精通多线程。 我有桌面应用程序,需要创建现有文件的只读临时副本,在其默认应用程序中打开文件,然后在用户完成查看后删除文件。

它必须以只读方式打开,因为用户可能会尝试将其保存为原始文件。

为此,我创建了一个新线程,它将文件复制到临时路径,设置文件属性,将Process处理程序附加到它,然后“等待”并在退出时删除文件。 这样做的好处是,即使在程序退出后线程仍将继续运行(看起来无论如何)。 这样,即使用户保持文件打开的时间比程序长,文件仍将被删除。

这是我的代码。 att object 保存了我的文件信息。

new Thread(() =>
{
      //Create the temp file name
      string temp = System.IO.Path.GetTempPath() + att.FileNameWithExtension;

      //Determine if this file already exists (in case it didn't delete)
      //This is important as setting it readonly will create User Access Control (UAC) issues for overwritting 
      //if the read only attribute exists
      if (File.Exists(temp)) { File.SetAttributes(temp, FileAttributes.Temporary ); }

      //Copy original file to temp location. Overwrite if it already exists due to previous deletion failure
      File.Copy(att.FullFileName, temp, true);

      //Set temp file attributes
      File.SetAttributes(temp, FileAttributes.Temporary | FileAttributes.ReadOnly);

      //Start process and monitor
      var p = Process.Start(temp);//Open attachment in default program
      if (p != null) { p.WaitForExit(); }

      //After process ends remove readonly attribute to allow deletion without causing UAC issues
      File.SetAttributes(temp, FileAttributes.Temporary);
      File.Delete(temp);
}
).Start();

我已经对其进行了测试,到目前为止它似乎正在完成这项工作,但这一切都让人感觉如此混乱。 老实说,我觉得应该有一种更简单的方法来处理这个问题,而不需要创建新线程。 如果首先考虑将文件复制到 memory 中,但我似乎无法弄清楚如何从MemoryStream在默认应用程序中打开它们。

所以我的问题是。

  1. 有没有更好的方法来实现打开不首先写入磁盘的文件的只读临时副本?
  2. 如果不是,我会从多线程方法中面临什么影响?

任何信息表示赞赏。

与其在关机时删除临时文件,不如在启动时删除“剩余”文件。

这通常比试图确保此类清理代码在进程终止时运行并处理那些“强制”情况(如电源故障、“kill -9”、“结束进程”等)更容易实现。

我喜欢为此类文件创建一个“临时”文件夹:我的所有应用程序都会在启动时扫描并删除此类文件夹中的任何文件,并且可以将代码添加到任何新项目中而无需更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM