使用 VB.NET 访问 %appdata%
如何通过VB.NET访问%appdata%中的文件?
例如,C:\Users\Kuzon\AppData\Roaming\program
。在另一台 Windows 7 计算机上如何访问该文件?另外,在 Windows XP 上您将如何执行此操作?我相信它是%Application Data%
。
How can you access files in %appdata% through VB.NET?
For example, C:\Users\Kuzon\AppData\Roaming\program
. How would I access that file, but on another Windows 7 machine? Also, how would you do it on Windows XP? I believe it is %Application Data%
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您编写 .NET 代码时,建议您使用专门为此目的设计的函数,而不是依赖环境变量,例如
%appdata%
。您正在寻找
Environment.GetFolderPath
方法,该方法返回您从Environment.SpecialFolder
枚举。应用程序数据文件夹由
Environment.SpecialFolder.ApplicationData
值表示。正如您所要求的,这是漫游应用程序数据文件夹。如果您不需要保存的数据在多台计算机之间漫游,并且希望其仅保留在一台计算机本地,则应使用Environment.SpecialFolder.LocalApplicationData
值。完整的示例代码:
是的,这在 C# 中的工作方式与 VB.NET 相同。
When you're writing .NET code, it's recommended that you use the functions explicitly designed for this purpose, rather than relying on environment variables such as
%appdata%
.You're looking for the
Environment.GetFolderPath
method, which returns the path to the special folder that you specify from theEnvironment.SpecialFolder
enumeration.The Application Data folder is represented by the
Environment.SpecialFolder.ApplicationData
value. This is, as you requested, the roaming application data folder. If you do not need the data you save to roam across multiple machines and would prefer that it stays local to only one, you should use theEnvironment.SpecialFolder.LocalApplicationData
value.Full sample code:
And yes, this works in C# the same as VB.NET.
当将 VB.NET 与 WinForms 一起使用时,这是另一种选择:
When using VB.NET with WinForms, this is another option:
它不仅知道应用程序数据在哪里,而且允许用户设置他们想要使用的默认文件夹。有些用户不是管理员,只能使用本地或漫游,但你确实不知道,所以你必须使用Try..Catch。此外,其他用户可能需要使用网络来访问数据,因此他们的工作文件夹是漫游。
对于任何用户,我允许他们设置自己的工作目录,并且还允许自定义文件夹,这通常适用于拥有自己的 PC/笔记本电脑的人,他们是自己的管理员。下面只是 My.Settings 命令。
我还创建了一个 OutputDirectory(文件夹),用于保存应用程序结果。 (如果他们可以访问正在使用的父工作目录,他们将拥有磁盘读写权限)。如果没有,他们必须让 IT 部门设置他们的权限。
It's not only knowing where the application data are, but rather, allowing users to set which folder they want to be used as default. Some users aren't administrators, and can only use local or roaming, but you really don't know, so you have to use Try..Catch. Also, other users may need to use a network to access data, so their working folder is Roaming.
For any user, I allow them set their working directory, and also allow for a custom folder, which is usually for people with their own PC/laptop, who are their own administrator. Below are just the My.Settings commands.
I also create an OutputDirectory (folder) into which application results are saved. (they will have disk read & write privileges if they can access the parent working directory in use). If not, they have to get their IT to set their privileges.