如何获取C#WinForms可执行文件所在的文件夹?
我的程序会生成一些临时文件,我想知道可执行文件的位置是否是放置它们的安全位置。
答案 0 :(得分:9)
如果文件只是临时文件,则应该使用以下内容:
string tempPath = System.IO.Path.GetTempPath();
这将为您提供当前用户的临时文件夹。这可能是一个更安全的赌注,然后尝试将它们写入exe的当前文件夹。
更多信息:http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx
答案 1 :(得分:8)
您可以使用从Assembly.GetExecutingAssembly().Location
:
string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
如果您只想生成临时文件,还可以使用Path.GetTempFileName()
获取文件名。
答案 2 :(得分:1)
首选将临时文件存储在临时目录中(如Dan Rigby所述)
string directory = System.IO.Path.GetTempPath();
但是如果您仍想在运行应用程序的目录中保存临时文件,那么您只需将Application.StartupPath
用于WinForms应用程序,
string directory = System.Windows.Forms.Application.StartupPath;