首页 > 解决方案 > 如何正确创建用于在 Windows 中打开的临时文件?

问题描述

好的,我有一些代码可以在很长一段时间内正常工作。但是,在一个站点上,我们的用户报告了一个错误,并且它特定于 rtf 文档,但我看不出该错误与该扩展名相关的方式或原因。

            string filename = System.IO.Path.GetTempFileName() + "." + fileext;
            File.WriteAllBytes(filename, filecontent);

            var process = Process.Start(filename);

错误是这个:

UnauthorizedAccessException: Access to the path 'C:\Users\admargosy\AppData\Local\Temp\180\tmp3D08.tmp.rtf' is denied.
Inner exception stack:
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)

到目前为止,用户已经确认如果它是 pdf 文件没有问题。它打开很好。Rtf 文件会遇到此错误。我有点需要知道如何分析这个或知道这里发生了什么。

应用程序在 WinForms 中,并在终端服务器上远程运行。

标签: c#.netwinforms

解决方案


这段代码对我有用:

string fileext = "txt";
byte[] filecontent = Encoding.UTF8.GetBytes("Hello, world!");
string filename = System.IO.Path.GetTempFileName() + "." + fileext;
File.WriteAllBytes(filename, filecontent);
var process = Process.Start(filename);

它将文本写入Hello, world!一个临时.txt文件并通过 shell 打开它(它可能会在干净的系统上的记事本中打开。)


在您的示例代码和相关错误中:

我会调查\180\片段是如何进入你的路径的。鉴于您提供的代码,它不应该在那里。你的例子有些可疑。

C:\Users\admargosy\AppData\Local\Temp\180\tmp3D08.tmp.rtf

我期待GetTempFileName返回的东西看起来更像C:\Users\admargosy\AppData\Local\Temp\tmp3D08.tmp


推荐阅读