C# 在 Windows 中保存临时文件的正确位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/752455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:49:00  来源:igfitidea点击:

Correct location to save a temporary file in Windows?

c#windows

提问by Scott

I have a file I need to write to a temp location, what is the best place in Windows? This file needs to not move as I need to read it a couple of times and dispose it when I close the program.

我有一个文件需要写入临时位置,Windows 中最好的位置是什么?这个文件不需要移动,因为我需要读取它几次并在我关闭程序时处理它。

采纳答案by tanascius

use

Path.GetTempPath();

or

或者

Path.GetTempFileName();

As commentator pointed out, GetTempFileName() is not threadsafe - but you can construct unique file names based on GUIDs.

正如评论员指出的那样, GetTempFileName() 不是线程安全的 - 但您可以根据 GUID 构造唯一的文件名。

回答by Mark Pim

Use the Windows API function GetTempPath()from System.IO.Path(see MSDN)

使用GetTempPath()来自System.IO.Path(参见MSDN)的 Windows API 函数

using System.IO

...

myTempPath = Path.GetTempPath();

You should be aware that the filesystem might well change during your program's execution. Either the Temp path may change (unlikely, granted), or your temporary file might have been moved or deleted by the user.

您应该意识到文件系统可能会在您的程序执行期间发生变化。临时路径可能会更改(不太可能,已授予),或者您的临时文件可能已被用户移动或删除。

Be prepared to check for its existence each time you access it and handle the case when it's not found gracefully.

准备好每次访问它时检查它是否存在,并在没有正常找到它时处理这种情况。

回答by EKS

The others beat me to it regarding

其他人打败了我

System.IO.Path.GetTempPath()

But you can also look into application data folder. That will allow you more control over your file, like the ability have 1 shared for all users or 1 per user.

但您也可以查看应用程序数据文件夹。这将使您能够更好地控制您的文件,例如可以为所有用户共享 1 个或每个用户共享 1 个。

Application.CommonAppDataPath
Application.UserAppDataPath

回答by Anderson Imes

If you need your application to write to a temporary location and work in partial trust, you'd need to look into IsolatedStorage.

如果您需要您的应用程序写入临时位置并在部分信任下工作,您需要查看IndependentStorage

回答by Fandango68

If you want to build your own custom temporary filename in reference to a temporary location, I use something like this, to strip off the PATH and apply my own filename ...

如果您想参考临时位置构建自己的自定义临时文件名,我会使用类似的方法来剥离 PATH 并应用我自己的文件名...

string wsPDFfile = Path.GetTempPath() + wsStudentID + "_" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".pdf";