[英]Getting a user specific path without knowing the username
I have a HTML file in C:\\Users\\myusername\\AppData\\Roaming\\myapp\\file.html
. 我在C:\\Users\\myusername\\AppData\\Roaming\\myapp\\file.html
有一个HTML文件。 I am accessing the file through a web Browser in my C# application to preview it from within the app. 我正在通过C#应用程序中的Web浏览器访问文件,以从应用程序中预览文件。
However, when the app is put onto another computer, the address in webBrowser1 is still specific to my username, and therefore other people cannot access the preview. 但是,将应用程序放置在另一台计算机上时,webBrowser1中的地址仍然是我的用户名专用的,因此其他人无法访问预览。
Is there a way to get to the file as a URL in my web Browser without having the hard coded username in the URL? 有没有一种方法可以在Web浏览器中以URL的形式获取文件而无需在URL中包含硬编码的用户名?
What I have tried: 我试过的
Thanks! 谢谢!
Here is the code I used after I was helped: 这是我得到帮助后使用的代码:
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string address = Path.Combine(folderPath + @"\myapp\file.html");
webBrowser1.Navigate(address);
If you want to get the name of the current logged in user you have to read Environment.UserName
property. 如果要获取当前登录用户的名称,则必须阅读Environment.UserName
属性。
Moreover if you need to access the AppData
directory for the roaming user you can get the folder path without hard-coding anything (do not forget that users directory isn't always c:\\users
on every Windows version and path for AppData
may vary too): 此外,如果您需要访问漫游用户的AppData
目录,则无需硬编码即可获取文件夹路径(不要忘记,在每个Windows版本上,users目录并不总是c:\\users
,并且AppData
路径也可能不同):
string folderPath = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
In you case simply append the file name: 在这种情况下,只需附加文件名:
string url = Path.Combine(folderPath, "file.htm");
Notes 笔记
If, for any reason, you need to use environment variables then you have first to expand them: 如果出于任何原因需要使用环境变量,则必须首先扩展它们:
string path = Environment.ExpandEnvironmentVariables(@"C:\Users\%USERNAME%\");
Have a look at this function. 看一下这个功能。 It returns the path of Current User's Application Data Folder. 它返回当前用户的应用程序数据文件夹的路径。
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.