c# - 如何正确创建用于在 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 中,并在终端服务器上远程运行。
解决方案
这段代码对我有用:
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
推荐阅读
- spring-boot - 使用基于令牌的机制实现基于提醒时间和用户身份验证发送提醒的后台服务。
- android - 如何在不建立新会话的情况下在 Camera2 API 中启用闪光灯?
- python - 基于多索引列数据框中的列范围进行切片
- python - Go 中的 gRPC 服务器和 Python 中的客户端之间的兼容性
- css - 如何让形状旋转 5s
- wordpress - 加载 CSS Wordpress 主题
- xamarin.forms - 尝试将启动画面添加到 Xamarin 表单时出错 -Xamarin Android
- python - BS4 的 Python HTML 解析
- java - 实现没有注解的 Spring 代码
- python - Python:按铃铛的顺序生成正态分布