简体   繁体   English

使用用户的用户名作为打开文件的路径

[英]Using the user's username as path for opening a file

I recently had to make a button in C# that simply had to open a text file. 最近,我不得不在C#中创建一个仅需打开文本文件的按钮。 The job was easy until I realized that I had no ideea how to open the file, why? 这项工作很容易,直到我意识到我对如何打开文件没有想法,为什么? Well simply because I can't think of a way to "define" the user's name in the path to the file. 好吧,仅因为我想不出一种在文件路径中“定义”用户名的方法。

Here is the code I tryed to use: 这是我尝试使用的代码:

private void button5_Click(object sender, EventArgs e)
{
    try
    {
        System.Diagnostics.Process.Start("C:\\Users\\%USERNAME%\\AppData\\Roaming\\SchoolProject\\file.txt");
    }
    catch { }
}

And, it did not work. 而且,它没有用。

So what's the solution to this problem? 那么该问题的解决方案是什么? If you feel like knowing the answer please be very explicit about it, I'm new to programming languages and I don't quite understand the codes so well. 如果您想知道答案,请非常明确地告诉我,我是编程语言的新手,我不太了解代码。 ( If you can and if it's not too much to ask please include the code that should work in your answer.) (如果可以的话,如果要求的不是太多,请在您的答案中包含应该起作用的代码。)

You can get to all of these "special" folder locations via the Environment.SpecialFolders enum and the GetFolderPath method. 您可以通过Environment.SpecialFolders枚举和GetFolderPath方法访问所有这些“特殊”文件夹位置。

In your case, you want SpecialFolder.ApplicationData . 在您的情况下,您需要SpecialFolder.ApplicationData Something like: 就像是:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test.txt");

All the special folders can be found on MSDN . 所有特殊文件夹都可以在MSDN上找到。

You need to expand environment variable use: Environment.ExpandEnvironmentVariables 您需要扩展环境变量的使用: Environment.ExpandEnvironmentVariables

Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string. 用等效于变量值的字符串替换指定字符串中嵌入的每个环境变量的名称,然后返回结果字符串。

Environment.ExpandEnvironmentVariables("C:\\Users\\%USERPROFILE%\\AppData\\Roaming\\SchoolProject\\file.txt");

This will give you the exact path. 这将为您提供确切的路径。

So your code could be: 因此,您的代码可能是:

string filePath = Environment.ExpandEnvironmentVariables("C:\\Users\\%USERPROFILE%\\AppData\\Roaming\\SchoolProject\\file.txt");
System.Diagnostics.Process.Start(filePath);

Also, having an empty try-catch will not help you in determining the exception, catch specific exception or at least base class Exception and then you can log/look in the debugger, at the exception and its message. 同样,使用空的try-catch不会帮助您确定异常,捕获特定的异常或至少捕获基类Exception ,然后您可以在调试器中记录/查看该异常及其消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM